Reputation: 124
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.
Upvotes: 1
Views: 1045
Reputation: 7880
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;
Upvotes: 2