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:
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;
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))
精彩评论