Many of the errors that I have corrected recently are the result of null references when accessing the navigation properties of objects loaded using the entity. I believe that there should be a flaw in the way I develop my methods. Here is an example ...
The task contains many roles, each role refers to the user.
public class Role { public int Id; public int User_Id; public string Type; } public class User { public int Id public string Name; } public class Task { public int Id; public string Name; public string Status; public List<Role> Roles; }
Given that I would request my context like this by mistake and not load the user ...
var task = context.Tasks.Include(x=>x.Roles).FirstOrDefault;
And then I call this method ...
public void PrintTask(Task task) { Console.WriteLine(task.Name); Console.WriteLine(task.Status); foreach(var r in task.Roles) { Console.WriteLine(r.User.Name);
I may have created this method with every intention of loading roles and user, but the next time I use it, I can forget that I need both. Ideally, a method definition should tell me what data is needed, but even if I pass both tasks and roles, I still miss Roles-> User.
What is the correct way to refer to these relationships and make sure they are loaded into something like this printing method? I'm interested in the best design, so "Use Lazy Loading" is not the answer I'm looking for.
Thanks!
EDIT:
I know I can load a task like this ...
var task = context.Tasks.Include(x=>x.Roles.Select(z=>z.User)).FirstOrDefault();
I want to know how I can create my method so that when I return and use it after 6 months, I know what data needs to be loaded into my entities? The definition of a method does not indicate what is needed to use it. Or how to block these NullReferences. There must be a better design.