【问题标题】:Linq to entities navigation propertiesLinq 到实体导航属性
【发布时间】:2014-03-24 16:52:43
【问题描述】:

在实体框架中,我有两个表(两个实体):具有一对多关系的人员和角色。 在人员表中,我有一个角色导航属性:

//People.cs
public virtual ICollection<Role> Role { get; set; }

现在我想检索所有具有“酒保”角色的人。我怎样才能做到这一点? 我想在查询表达式方法中对实体使用 linq。我试过了:

var listPerson = (from p in SiContext.People
                 where p.Role.Name = 'barman'
                 select p).ToList();

问题是我无法创建 p.Ruolo.Name,因为 p.Ruolo 是一个没有属性“Name”的 ICollectionType(而实体 Role 具有该属性)

【问题讨论】:

    标签: c# linq entity-framework


    【解决方案1】:

    由于角色是一个集合,所以需要使用Any

    var listPerson = (from p in SiContext.People
                     where p.Role.Any(x => x.Name == "barman")
                     select p).ToList();
    

    【讨论】:

      【解决方案2】:

      只是为了补充您的代码,包括 ToLower()

      var listPerson = (from p in SiContext.People
                       where p.Role.Any(x => x.Name.ToLower() == "barman")
                       select p).ToList();
      

      【讨论】:

        【解决方案3】:

        您可以尝试按顺序排列(假设您有反向导航属性)

        var listPerson = SiContext.Role.First(r => r.Name == "barman").People.ToList();
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-10-08
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多