繁体   English   中英

.NET Entity Framework 代码优先:未加载导航属性

[英].NET Entity Framework code-first: navigation properties are not loaded

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

其中两个是Person 和Company,它们是多对多的关系。

因此,在我的代码中,我有一个 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



}

我的通灵调试能力告诉我延迟加载已启用并且您没有使用正确的包含。

首先,您需要确保您有以下 using 语句

using System.Data.Entity

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

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

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

注意:对于仅在执行查询时访问的字段,您不需要包含。 IE

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

暂无
暂无

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

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