在查询结果中包括来自连接的对象
本文关键字:自连接 对象 包括 查询 结果 | 更新日期: 2023-09-27 18:17:28
想象一个从数据库生成上下文的简单实体框架查询,如:
var q = from a in context.Accounts
join c in context.Contracts
on a.Id equals c.AccountId
select new CustomAccount {
Id = a.Id,
Name = a.Name,
...
Contracts = //How do I easily populate the related contracts?
};
查询查找帐户和连接到契约。这种关系在数据库中没有强制执行(我不能更改模式),因此我不能使用导航属性。是否有一种简单的方法可以填充相关对象?
只使用group by
子句。像这样(未经测试):
var q = from a in context.Accounts
join c in context.Contracts on a.Id equals c.AccountId
group a by new { a.Id, a.Name, a.Etc } into g
select new CustomAccount
{
Id = g.Key.Id,
Name = g.Key.Name,
Etc = g.Key.Etc,
Contracts = g.SelectMany(x => x.Contracts)
};
我不确定我是否理解正确,但你可以执行一个查询,返回匿名类型对象
EDIT:您可以创建一个自定义类来保存结果的数据成员,并在linq结果中返回。
EDIT: using group by on account name(例如)
var q = from a in context.Accounts
join c in context.Contracts
on a.Id equals c.AccountId
group a by new { a.Name } into g
select new AccountContracts
{
AccountName = g.Key.Id, // Account name
Contracts = g.SelectMany(x => x.Contracts)
};