问题描述
在实体框架中,我有两个表(两个实体):具有一对多关系的人员和角色.在人员表中,我有一个角色导航属性:
//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 具有该属性)
推荐答案
由于role是一个集合,所以需要使用Any
var listPerson = (from p in SiContext.People where p.Role.Any(x => x.Name == "barman") select p).ToList();
问题描述
In entity framework i have two table (two entities): People and Role with one to many relationship. In the People tables i have a navigation property to Role:
//People.cs public virtual ICollection<Role> Role { get; set; }
Now i want retrieve all people that have role as 'barman'. How can i achieve this? I want use linq to entities in the query expression method. I've tried:
var listPerson = (from p in SiContext.People where p.Role.Name = 'barman' select p).ToList();
The problem is that i cannot make p.Ruolo.Name because p.Ruolo is a ICollectionType that doesn't have the property "Name" (while the entity Role has that property)
推荐答案
Since role is a collection, you need to use Any
var listPerson = (from p in SiContext.People where p.Role.Any(x => x.Name == "barman") select p).ToList();