如何用EF代码编写Linq查询首先是多对多的关系

时间:2015-03-24 00:25:19

标签: c# sql linq entity-framework ef-code-first

我首先使用EF代码,我在ProviderDepartment之间创建了多对多关系。

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|
--------------------------

任何帮助都将不胜感激。

1 个答案:

答案 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;