LINQ-to-Entities:嵌套列表的条件加载
我有一个具有以下层次结构的对象
class Account
string username
List Delegations
class Delegation
List SingleDelegations
class SingleDelegation
string uid
现在我想执行一个查询,该查询加载一个 Account
对象,该对象具有已加载的相应依赖项(即代表团和代表团.SingleDelegations)(使用该单个查询), 但是它应该只加载那些匹配指定条件的帐户,即
- 仅加载那些用户名与参数匹配的帐户(简单)
- 仅加载那些uid与给定参数匹配的
SingleDelegation
对象
<强>我的方法
我的 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;
}
这显然返回一个匿名类型对象,该对象具有作为属性公开的不同对象。由于 Account
和 Delegation
和 SingleDelegation
通过相应的 FK 链接,我的 Account
对象将正确加载它们(如上下文知道它们)。
就个人而言,这看起来很奇怪。我必须创建一个新的匿名类型来指示 EF 在查询 st 中包含子对象,最后我正确加载了我的 Account
对象。
我的问题:
有没有更好、更好的方法?
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
SingleDelegation
objects 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,没有更好或更好的方法。这就是 EF 的工作原理。如果要过滤关系并使用单个查询检索所有数据,则必须始终使用投影。
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.