Linq to Entities Group紧随其后

时间:2018-06-15 10:02:02

标签: entity-framework group-by linq-to-entities

我想将以下SQL编写为Linq to Entities语句

select min(enddate), Code 
from t1
inner join t2
on t1.t2id = t2.id
group by Code

到目前为止我所拥有的是

var data = ctx.t1.Join(ctx.t2,
                        one => one.t2id,
                        two => two.Id,
                        (one, two) => new {one, two})
                    .GroupBy(onetwo => onetwo.one.t2id)
                    .Min(onetwo => WHAT GOES HERE?);

我认为我唯一遗漏的是WHAT GOES HERE?中的内容。我可能是错的,完全误入歧途,但据我所知,这是我唯一遗漏的东西。知道我能做什么吗?

1 个答案:

答案 0 :(得分:1)

您应该使用的是Select而不是Min,否则您只能返回单个值。例如,像这样:

var data = ctx.t1
    .Join(ctx.t2, one => one.t2id, two => two.Id, (one, two) => new {one, two})
    .GroupBy(onetwo => onetwo.one.t2id)
    .Select(x => new 
    {
        Code = x.Key, 
        MinDate = x.Min(g => g.one.EndDate) //This may need to be g.two.EndDate
    });