Entity Framework条件性的ThenInclude,基于之前的Include。

huangapple go评论78阅读模式
英文:

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();

huangapple
  • 本文由 发表于 2023年6月29日 23:30:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76582532.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定