我首先使用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");
});
我正在尝试编写一个与以下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%'
结果应该是提供者和部门,其中Provider.LastName或Department.Name以'er'开头。
--------------------------
| LastName | Name |
--------------------------
| Selfa | ER |
| Erickson | Radiology|
--------------------------
任何帮助都将不胜感激。
答案 0 :(得分:2)
在这种情况下,似乎您正确实现了many-to-many
关联。所以对于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;