.NET实体框架代码优先:未加载导航属性

时间:2015-09-01 15:24:06

标签: c# .net entity-framework

在我的应用程序中,我有很多实体。

其中两个是人与公司,它们具有多对多的关系。

因此,在我的代码中,我有一个Person类,其中包含对公司集合(ICollection)的引用,以及一个包含对一组人的引用的Company类。 (ICollection的)。

使用第一代码方法,正确生成了数据库。 有三个表:人员,公司和人民公司。

在PeopleCompanies表中,我有一条记录,应该在确定的人与另一家公司之间建立关联,如下图所示。

http://s27.postimg.org/xnkz3j94j/DBPrint.png

那么,我的问题是什么?

在我的业务逻辑中,我需要知道哪些人与确定的公司相关联,但公司类的导航属性仍为空:ICollection.Count()-----> 0

在现实中,正如您在上图中所看到的,只有一个人与公司相关联。

我需要导航属性!

有人可以帮忙吗?

DbContext的代码如下。谢谢!

 public class EnterpriseDataContext : DbContext
{
    public EnterpriseDataContext(string connString) : base(connString)
    {

    }


    #region CRM Module

    public DbSet<Category> Categories { get; set; }
    public DbSet<City> Cities { get; set; }
    public DbSet<Company> Companies { get; set; }
    public DbSet<CompanyNote> CompanyNotes { get; set; }
    public DbSet<Country> Countries { get; set; }
    public DbSet<Lead> Leads { get; set; }
    public DbSet<Person> People { get; set; }
    public DbSet<PersonNote> PersonNotes { get; set; }
    public DbSet<Sector> Sectors { get; set; }

    #endregion



}

1 个答案:

答案 0 :(得分:1)

我的通灵调试功能告诉我启用了延迟加载,而您没有使用正确的包含。

首先,您需要确保使用以下语句

using System.Data.Entity

然后使用.Include()加载您的人员。

var myEnterpriseDataContext = new EnterpriseDataContext("insert connection string here");

myEnterpriseDataContext.Companies
    .Include(c => c.People)
    //.Rest Of Query

注意:您不需要在执行查询时只能访问的字段包含。即。

myEnterpriseDataContext.Companies
    .Select(c => new CompanyViewModel(){People = c.People});