I have a situation where I’d like to eager load the organization property of a user being retrieved from the DB using LINQ-to-SQL (because of my using here attempts to get the property later fail because the context’s connection is closed). The problem is that sometimes the user does not have an organization. In that case FetchUserByName returns null. Not what I want at all. Is there a way to get this to work the way I want, which is to return an instance of user whether they have an associated organization or not?
private static void EagerLoad(DataContext ctx)
{
var loadOpt = new DataLoadOptions();
loadOpt.LoadWith<User>(u => u.Organization);
ctx.LoadOptions = loadOpt;
}
public User FetchUserByName(string username)
{
User user = null;
using (var ctx = contextManager.GetSingleDataContext())
{
EagerLoad(ctx);
user = ctx.GetTable<User>().SingleOrDefault(u => u.UserName == username && u.IsActive);
}
return user;
}
Documenting what the fix was for others who may run into this.
LoadWithactually determines whether to use anINNER JOINor anOUTER LEFT JOINin the SQL created by LINQ-to-SQL by looking whether the foreign key in the data model class is nullable in the database. If it is nullable it uses the outer join.Changed the one line to:
And then everything worked as expected.