简体   繁体   English

首先与代码建立多对多关系的Map View

[英]Map View with many to many relationship with code first

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. 这是我发现的唯一描述了类似问题post1的帖子 ,但是它并不能解决我的问题。

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. 我首先为我的应用程序使用EF6.1代码,并且需要为其添加视图并定义多对多关系。

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: 在模型构建器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. 在数据库中,我得到了一个映射表EmployeeLocations,并且一切正常。

Now I want to add a view - sort of an employee extension. 现在,我想添加一个视图-一种员工扩展。 I've got this view in the DB and related paco class: 我在数据库和相关的paco类中有此视图:

      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); 我为其添加了DbSet和此配置:this.HasKey(e => e.EmployeeID); this.ToTable("EmployeeLocations "); 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): 或通过在查询中添加.include(e => e.Locations)来显式添加(您需要添加名称空间System.Data.Entity才能使其工作):

var employeeItem = context.Employee.Include(e => e.Locations).FirstOrDefault(x => x.EmployeeName == "Bob");

Hope that helps! 希望有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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