There is an issue am struggling with for a while. This is the only post I found that describes similar problem post1 , but it doesn't solves mine.
I am using a EF6.1 code first for my app and need to add a view and define many-to-many relationship for it.
Consider this:
public class Employee
{
public int EmployeeId { get; set; }
public int EmployeeName { get; set; }
ICollection<Location> Locations {get; set;}
}
public class Location
{
public int LocId { get; set; }
public int LocName { get; set; }
}
in model builder OnModelCreating:
modelBuilder.Entity<Employee>().HasMany<Location>(t => t.Locations)
.WithMany().Map(mc =>
{
mc.ToTable("EmployeeLocations");
mc.MapLeftKey("EmployeeId");
mc.MapRightKey("LocId");
});
In db I get a mapping table EmployeeLocations and everything works fine.
Now I want to add a view - sort of an employee extension. I've got this view in the DB and related paco class:
public class Employee
{
public int EmployeeId { get; set; }
public int EmployeeName { get; set; }
public string SomeOtherProp {get; set;}
ICollection<Location> Locations {get; set;}
}
I've added a DbSet for it and this configuration: this.HasKey(e => e.EmployeeID); this.ToTable("EmployeeLocations ");
It populates fine and I am able to query it, but without the Locations - it is always empty.
does any one knows how can I define this many-to-many relationship?
Going by your models, you're not loading related entities (Locations). You'll need to mark the collection as virtual to populate it automatically (lazy loading):
public virtual ICollection<Location> Locations {get; set;}
Or explicitly by adding .Include(e => e.Locations) in your queries (You'll need to add the namespace System.Data.Entity for it work):
var employeeItem = context.Employee.Include(e => e.Locations).FirstOrDefault(x => x.EmployeeName == "Bob");
Hope that helps!
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.