【问题标题】:Map View with many to many relationship with code first地图视图与代码的多对多关系优先
【发布时间】:2014-10-19 15:38:02
【问题描述】:

有一个问题正在努力解决一段时间。 这是我发现的唯一一篇描述类似问题post1 的帖子,但它并没有解决我的问题。

我首先为我的应用使用 EF6.1 代码,需要添加一个视图并为其定义多对多关系。

考虑一下:

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

在模型构建器 OnModelCreating 中:

            modelBuilder.Entity<Employee>().HasMany<Location>(t => t.Locations)
            .WithMany().Map(mc =>
            {
                mc.ToTable("EmployeeLocations");
                mc.MapLeftKey("EmployeeId");
                mc.MapRightKey("LocId");
            });

在 db 中,我得到一个映射表 EmployeeLocations,一切正常。

现在我想添加一个视图 - 一种员工扩展。我在 DB 和相关的 paco 类中有这个视图:

      public class Employee
{
    public int EmployeeId { get; set; }

    public int EmployeeName { get; set; }

     public string SomeOtherProp {get; set;}
    ICollection<Location> Locations {get; set;}
}

我已经为它添加了一个 DbSet 和这个配置: this.HasKey(e => e.EmployeeID); this.ToTable("EmployeeLocations");

它填充得很好,我可以查询它,但没有位置 - 它总是空的。

有人知道我该如何定义这种多对多关系吗?

【问题讨论】:

    标签: c# ef-code-first


    【解决方案1】:

    按照您的模型,您不会加载相关实体(位置)。您需要将集合标记为虚拟以自动填充它(延迟加载):

    public virtual ICollection<Location> Locations {get; set;}
    

    或通过在查询中显式添加 .Include(e => e.Locations) (您需要添加命名空间 System.Data.Entity 才能使其工作):

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

    希望有帮助!

    【讨论】:

    • 我没有提到它,但我做了包含但没有找到任何位置。
    猜你喜欢
    • 2011-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多