LINQ to SQL,选择具有最大日期的目标

时间:2010-03-17 12:50:44

标签: linq linq-to-sql join group-by

我最终得到了下面这个可怕的代码,我现在无法获得更好的结果。 有什么更好的方法呢?

这是关于我数据库的这一部分:

Hosted by imgur.com

修改

PatientSubscription到多个MonitoringObjectsTarget条记录引用了这些Subscriptions。我想检索目标记录,其中Subscription的{​​{1}}和Patient Category的最新日期为MonitoringObjects。这些目标记录可能具有不同的最长日期,因为Targets可以Subscriptions独立地添加MonitoringsObjects

var subs = db.Subscriptions.Where(p => p.PatientID == patID).Where(p => p.MonitoringObject.Category.Name == "Medication");


var targets1 = from t in db.Targets
              where subs.Contains(t.Subscription)
              select t;

var maxTa = from t in db.Targets
            group t by t.SubscriptionID
                into g
                select new
                {
                    Ky = g.Key,
                    Date = g.Max(p => p.Date)
                };
var targets2 = from t in targets1
               where maxTa.Select(p => p.Ky).Contains( t.SubscriptionID ) && 
               maxTa.Select(p => p.Date).Contains( t.Date )
               select t;

1 个答案:

答案 0 :(得分:1)

我不确定这是想要实现什么,或者你的数据模型是什么样的,但是这样的东西?

var subs = db.Subscriptions.Where(p => p.PatientID == patID).Where(p => p.MonitoringObject.Category.Name == "Medication");

var targets = subs
    .SelectMany(s => s.Targets)
    .Where(t => t.Date == t.Subscription.Targets.Max(_t => _t.Date))
相关问题