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;
}