通过linq查询获取组中最新记录的ID

时间:2018-01-24 12:56:11

标签: entity-framework linq

下面的这个linq查询包含一些连接,我需要获取一个实体的最新记录ID,其id字段是' sonuc'

var query = (from type1 in lohusaHastaRepo
    join type2 in hastaRepo on lohusa.HastaTC equals hasta.HastaTC
    join type3 in gebeSonucBildirimRepo on lohusa.HastaTC equals sonuc.HastaTC
    group type1 by hasta.HastaTC into grp
    select new SomeModel()
    {
        Type3ID = 0,//I want to get 'ID' of latest records of 'sonuc' entity 
        Type1ID = grp.OrderByDescending(o=>o.BirthDate).Select(s=>s.ID).FirstOrDefault()
    });

此:

grp.OrderByDescending(o=>o.DogumTarihiResmi).Select(s=>s.ID).FirstOrDefault()
上面的

给了我' type1'实体,我还需要' type3'的Id。

我该怎么做?

1 个答案:

答案 0 :(得分:0)

我认为这应该有效:

var query = (from type1 in lohusaHastaRepo
    join type2 in hastaRepo on lohusa.HastaTC equals hasta.HastaTC
    join type3 in gebeSonucBildirimRepo on lohusa.HastaTC equals sonuc.HastaTC
    group new {type1, type3} by hasta.HastaTC into grp
    select new SomeModel()
    {
        Type3ID = grp
            .Select(e => e.type3)
            .OrderByDescending(o=>o.BirthDate)
            .Select(s=>s.ID)
            .FirstOrDefault(),
        Type1ID = grp
            .Select(e => e.type1)
            .OrderByDescending(o=>o.BirthDate)
            .Select(s=>s.ID)
            .FirstOrDefault(),
    });
但是,我不能说它的表现如何。您可能希望在大型数据集上对其进行测试,并考虑将其拆分为两个单独的往返行程:

var type1IDs = sonuc.GroupBy(s => s.HastaTC)
    .Select(g => new 
    {
        HastaTC = g.Key,
        ID = g.OrderByDescending(o=>o.BirthDate)
            .Select(s=>s.ID)
            .FirstOrDefault()
    });

var type3IDs = lohusa.GroupBy(s => s.HastaTC)
    .Select(g => new 
    {
        HastaTC = g.Key,
        ID = g.OrderByDescending(o=>o.BirthDate)
            .Select(s=>s.ID)
            .FirstOrDefault()
    });