簡體   English   中英

在 EF Core 中過濾“包含”實體

[英]Filtering "include" entities in EF Core

我有以下型號

 public class Person
{
    public int PersonId { get; set; }
    public string Name { get; set; }
    public List<PersonRole> PersonRoles { get; set; }

}

public class RoleInDuty
{
    public int roleInDutyId { get; set; }
    public string Name { get; set; }
    public int typeOfDutyId { get; set; }
    public TypeOfDuty typeOfDuty { get; set; }
    public List<PersonRole> PersonRoles { get; set; }

}
public class PersonRole
{
    public int PersonId { get; set; }
    public Person Person { get; set; }
    public int RoleInDutyId { get; set; }
    public RoleInDuty RoleInDuty { get; set; }
}

現在我可以使用以下代碼加載所有人的所有角色:

 var  people = _context.Persons
      .Include(p => p.PersonRoles)
        .ThenInclude(e => e.RoleInDuty).ToList();

但我不想將所有數據加載到 List,我需要根據輸入的 typeOfDutyId 加載 PersonRole。 我正在嘗試使用以下代碼解決此問題

people = _context.Persons
  .Include(p => p.PersonRoles
    .Where(t=>t.RoleInDuty.typeOfDutyId == Id)).ToList();

但是VS拋出錯誤

InvalidOperationException: Include 屬性 lambda 表達式 'p => {from PersonRole t in p.PersonRoles where ([t].RoleInDuty.typeOfDutyId == __typeOfDuty_typeOfDutyId_0) select [t]}' 無效。 該表達式應表示屬性訪問:'t => t.MyProperty'。 要定位在派生類型上聲明的導航,請指定目標類型的顯式類型化 lambda 參數,例如“(Derived d) => d.MyProperty”。 有關包含相關數據的詳細信息,請參閱http://go.microsoft.com/fwlink/?LinkID=746393

據我了解,我無法訪問屬性RoleInDuty.typeOfDutyId,因為我還沒有包含它。

我用下面的代碼解決了這個問題

people = _context.Persons
  .Include(p => p.PersonRoles)
    .ThenInclude(e=>e.RoleInDuty).ToList();       
foreach (Person p in people)
{
  p.PersonRoles = p.PersonRoles
    .Where(e => e.RoleInDuty.typeOfDutyId == Id)
    .ToList();
}

devnull顯示下一個如何在實體框架中過濾“包含”實體? ,並且有同樣的問題,我閱讀了它,並找到了答案。 解決我的問題可以用下一個:

var temp = _context.Persons.Select(s => new
  {
    Person = s,
    PersonRoles= s.PersonRoles
      .Where(p => p.RoleInDuty.typeOfDutyId == this.typeOfDuty.typeOfDutyId)
      .ToList()
  }).ToList();

最后,在 Include with ef core 5 中過濾。 MSDN 文檔中的詳細信息: https : //docs.microsoft.com/en-us/ef/core/querying/related-data#filtered-include

Var people = _context.Persons
                     .Include(p => p.PersonRoles
                                    .Where(t=>t.RoleInDuty.typeOfDutyId == Id))
                     .ToList();

var blogs = context.Blogs
                   .Include(e => e.Posts.OrderByDescending(post => post.Title).Take(5)))
                   .ToList();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM