英文:
Entity Framework conditional ThenInclude based on preceding Include
问题
在EF7中,根据先前Include的值条件性地使用ThenInclude加载项,您可以使用以下方式:
var cse = context.Cases
.Include(c => c.Logs.Select(l => new { Log = l, LoadLogText = l.Type == 1 }))
.ToList()
.Select(c =>
{
c.Logs = c.Logs.Where(l => !l.LoadLogText || l.Type == 1).ToList();
return c;
});
这将加载所有Logs,但仅对Type等于1的Logs加载LogText。
英文:
In EF7, how can I conditionally ThenInclude an item, based on the value of a prior Include?
I have a Case object which contains many Logs. Each Log contains a LogText.
class Case
{
public int Id { get; set; }
public ICollection<Log> Logs { get; set; }
}
class Log
{
public int Id { get; set; }
public int CaseId { get; set; }
public Case Case { get; set; }
public int Type { get; set; }
public LogText LogText { get; set; }
}
class LogText
{
public string Text { get; set; }
}
I want to load a particular Case, and all of its Logs, but I only want to load the LogText for particular Logs based on their Type.
I can load all the Logs/LogText via:
var cse = context.Cases.Include(c => c.Logs).ThenInclude(l => l.LogText);
I can load only the Logs matching my Type filter via:
var cse = context.Cases.Include(c => c.Logs.Where(l => l.Type==1)).ThenInclude(l => l.LogText);
But, I can't work out how to include all Logs, but only LogText for Logs which have Type==1
Any suggestions?
答案1
得分: 1
根据我看到的情况,我唯一的选择是加载经过筛选的Include/ThenInclude,然后事后显式加载完整的Logs集合。这意味着需要两次访问数据库而不是一次,这并不理想。
var cse = context.Cases.Include(c => c.Logs.Where(l => l.Type == 1)).ThenInclude(l => l.LogText).FirstOrDefault();
context.Entry(cse).Collection(c => c.Logs).Query().Load();
英文:
As far as I can see, the only option I have is to load the filtered Include/ThenInclude and after the fact, explicity load the full Logs collection. This means two database hits instead of one, which is not ideal.
var cse = context.Cases.Include(c => c.Logs.Where(l => l.Type==1)).ThenInclude(l => l.LogText).FirstOrDefault();
context.Entry(cse).Collection(c => c.Logs).Query().Load();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论