在EF Core中过滤“包含”实体

时间:2019-01-26 00:29:25

标签: c# asp.net-core entity-framework-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:包含属性lambda表达式'p   => {从p.PersonRoles中的PersonRole t,其中([t] .RoleInDuty.typeOfDutyId == __typeOfDuty_typeOfDutyId_0)选择   [t]}'无效。该表达式应表示属性访问:   't => t.MyProperty'。要定位在派生类型上声明的导航,   指定目标类型的显式输入的lambda参数,例如   '(派生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();
}

2 个答案:

答案 0 :(得分:1)

最后,过滤包含在ef核心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();

答案 1 :(得分:0)

devnull显示下一个 How to filter "Include" entities in entity framework?,同样的问题,我阅读并找到了答案。解决我的问题可以用下:

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