LINQ to SQL, select targets with max date

2019-09-06 23:34发布

I ended up with this horrible code below, I can't get a better result now. What is a better way of doing that?

It's about this part of my database:

Hosted by imgur.com

EDIT

A Patient has a Subscription to multiple MonitoringObjects. Target records refer to these Subscriptions. I want to retrieve the target records with the newest date per Subscription for a given Patient and a Category of MonitoringObjects. These target records may have different max dates, as Targets can be added for Subscriptions to MonitoringsObjects independently.

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条回答
Animai°情兽
2楼-- · 2019-09-07 00:21

I am not exactly sure what this is trying to achieve, or what your datamodel looks like, but something like this?

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))
查看更多
登录 后发表回答