想象一个简单的实体框架查询,其中包含从数据库生成的上下文,例如:
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?
};
查询查找帐户并加入合同。该关系未在数据库中强制执行(我无法更改架构),因此我无法使用导航属性。有没有一种简单的方法可以填充相关的对象?
答案 0 :(得分:0)
我不确定我是否理解正确,但您可以执行返回匿名类型对象的查询
编辑:您可以创建一个自定义类来保存结果的数据成员并返回linq结果。
编辑:在帐户名称上使用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.Name } into g
select new AccountContracts
{
AccountName = g.Key.Id, // Account name
Contracts = g.SelectMany(x => x.Contracts)
};
答案 1 :(得分:0)
只需使用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)
};