我正在努力构建一个提供单个最小值的linq查询。但是,我一直得到错误的最小值。我确定这是一个加入问题,但我无法获得外部联接。我已根据其他帖子尝试了一些外连接,但无法使任何工作正常运行。我不确定哪个表需要外连接才能完成这项工作。我想我已经尝试过我能想到的每一个组合。
这是我开始的查询:
(from r in Results
join entry in Entries on r.EntryId equals entry.EntryId
join entryEvent in EntryEvents on entry.EntryId equals entryEvent.EntryId
join eswimmer in EntrySwimmers on entry.EntryId equals eswimmer.EntryId
where eswimmer.SwimmerId == 12027 && entryEvent.EventNumberId == 1233
select r.Time)
.Min();
外部联接尝试:
from r in Results
join en in Entries on r.EntryId equals en.EntryId
join ev in EntryEvents on en.EntryId equals ev.EntryId into evJoined
join s in EntrySwimmers on en.EntryId equals s.EntryId into sJoined
from ev in evJoined.DefaultIfEmpty()
from s in sJoined.DefaultIfEmpty()
where (s.SwimmerId == 12027 && ev.EventNumberId == 1233)
select r.Time;
问题在于我从游泳者的所有结果中获得最小值,而不是游泳者和特定事件的最小值。
类结构如下所示:
结果
public int ResultId
public int EntryId
public ICollection<Entry> Entry
public int EntryEventId
public ICollection<EntryEvent> EntryEvent
public TimeSpan Time
条目
public int EntryId
public ICollection<EntrySwimmer> EntrySwimmers
public Result Results
public ICollection<EntryEvent> EntryEvents
EntryEvents
public int EntryEventId
public int EventNumberId
public EventNumber EventNumbers
public int EntryId
public Entry Entry
EntrySwimmers
public int EntryId
public Entry Entries
public int SwimmerId
public Swimmer Swimmers
我还在学习linq,加入等等。所以解释得到了解释。提前谢谢!
答案 0 :(得分:0)
您已经映射了导航属性,所以基本上您不需要任何联接,因为您的ORM将为您提供:
var min = Results
.Include(x => x.Entry.Select(y => y.EntrySwimmers)) //here you should rename Entry to Entries ideally in your result class
.Include(x => x.Entry.Select(y => y.EntryEvents))
.Where(x => x.Entry.EntrySwimmers.Any(y => y.SwimmerId == 12027) && x.EntryEvents.Any(y => y.EventNumberId == 1233))
.Min(x => x.Time);
不确定为什么你在Result和Entry中都有事件。