简体   繁体   中英

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 .

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.

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

--------------------------
| 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. so with Linq you don't need the join also use StartsWith for '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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM