I have an object with the following hierarchy
class Account
string username
List Delegations
class Delegation
List SingleDelegations
class SingleDelegation
string uid
Now I’d like to perform a query which loads an Account object with the according dependencies (i.e. Delegations and Delegations.SingleDelegations) already loaded (with that single query), but it should just load those matching a specified condition, namely
- only those accounts where the username matches a parameter (easy)
- only those
SingleDelegationobjects where the uid matches a given parameter
My Approach
I have the following method in my AccountRepository
public Account ReadAccountsByUsernameAndUid(string username, string uid)
{
var matchingObjs = (from a in context.Accounts
from d in a.Delegations
from sd in d.SingleDelegations
where
a.username == username &&
sd.uid == uid
select new
{
Account = a,
Delegation = d,
SingleDelegation = sd
});
//knowing there should be just one account (ignore the missing null check for now)
return matchingObjs.FirstOrDefault<Account>().Account;
}
This obviously returns an anonymous type object having the different objects exposed as properties. Since the Account and Delegation and SingleDelegation are linked over corresponding FKs my Account object will have them properly loaded (as the context knows them).
Personally, this looks weird. I have to create a new anonymous type for instructing EF to include the subobjects in the query s.t. in the end I get my Account object properly loaded.
My Question:
Is there a better, nicer way?
No there is no better or nicer way. This is how EF works. If you want to filter relations and retrieve all data with single query you must always use projection.