[英]how to write a Linq query with a EF code first Many to Many relationship
I'm using EF code first, where I have created a many-to-many relationship between Provider
and Department
. 首先,我使用EF代码,在
Provider
和Department
之间创建了多对多关系。
public class Provider
{
public int Id { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public virtual ICollection<Department> Departments { get; set; }
}
public class Department
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Provider> Providers { get; set; }
}
modelBuilder.Entity<Provider>()
.HasMany(p => p.Departments)
.WithMany(d => d.Providers)
.Map(m =>
{
m.MapLeftKey("ProviderId");
m.MapRightKey("DepartmentId");
m.ToTable("ProviderDepartment");
});
I'm trying to write a linq query that would be equivalent to the below SQL query, but the ProviderDepartment table is not part of the DbContext. 我正在尝试编写一个与下面的SQL查询等效的linq查询,但ProviderDepartment表不是DbContext的一部分。
select p.LastName, d.Name
from Provider p
join ProviderDepartment pd on p.Id = pd.ProviderId
join Department d on pd.ProviderId = d.Id
where d.Name like 'er%'
or p.LastName like 'er%'
The result should be the Provider and Department where either the Provider.LastName or Department.Name start with 'er'. 结果应该是提供者和部门,其中Provider.LastName或Department.Name以'er'开头。
--------------------------
| LastName | Name |
--------------------------
| Selfa | ER |
| Erickson | Radiology|
--------------------------
Any help would be appreciated. 任何帮助,将不胜感激。
in this case as seems that you implemented the many-to-many
association correctly. 在这种情况下,您似乎正确实现了
many-to-many
关联。 so with Linq you don't need the join
also use StartsWith
for 'er%'
: 所以使用LINQ,你不需要
join
也使用StartsWith
为'er%'
:
var query = from p in DbContext.Provider
from d in p.Departmennt
where p.Lastname.StartsWith("er") && d.Name.StartsWith("er")
select p.LastName,d.Name;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.