我有一个像
这样的表格结构Table_A
Id Description
1 A
2 B
3 C
4 D
Table_B
Table_A_Id Id Description
1 1 A
1 2 B
2 3 C
2 4 D
3 5 E
3 6 F
4 7 G
4 8 H
4 9 I
4 10 J
我希望以某种方式加入它们以获取以下类的列表
Public Resultset
{
public Table_A table_a {get;set;}
public List<Table_B> table_b {get;set;}
}
//假设我们根据表定义
有Table_A和Table_B的类以下是我的尝试
var filter [] = {1,3,5};
var query = from a in context.Table_A
joins b in context.Table_B
on a.Id equals b.Table_A_id
where filter.Contains(b.Id)
// Need something here perhaps to group it to get desired results
Select new ResultSet()
{
// what to do here
}
答案 0 :(得分:2)
您可以通过以下方式尝试以下群组:
var query = from a in context.Table_A
joins b in context.Table_B
on a.Id equals b.Table_A_id
where filter.Contains(b.Id)
group new{A=a, B=b } by a.Id into g
select new ResultSet()
{
table_a=g.FirstOrDefault().A,
table_b=g.Select(e=>e.B).ToList()
};
如果您在这些实体之间使用navigation properties,则另一种方式:
var query = from b in context.Table_B
where filter.Contains(b.Id)
group b by b.Table_A_id into g
select new ResultSet()
{
table_a=g.FirstOrDefault().A,
table_b=g.ToList()
};
答案 1 :(得分:1)
我认为你需要一个简单的Group Join:
var filter = new [] { 1, 3, 5 };
var query = from a in context.Table_A
join b in (from b in context.Table_B where filter.Contains(b.Id) select b)
on a.Id equals b.Table_A_id into items_B
select new ResultSet
{
table_a = a,
table_b = items_B.ToList()
};