【问题标题】:EF Code First - Many To ManyEF 代码优先 - 多对多
【发布时间】:2013-11-19 21:24:55
【问题描述】:

我在首先在代码中设计多对多关系时遇到了问题。 EF 正在创建 Junction 表并按照我的预期关联 Fk,但是当我尝试访问用户的 MailingList 集合时,没有条目。

我已经在 Initialise via Seeding 上实现了测试数据,数据都存在于数据库中。

我认为问题在于用户和邮件列表的构造函数,但我不确定。我希望能够导航 User.MailingLists 的导航属性。

    var user = db.Users.Find(1);

    Console.WriteLine("{0}", user.EmailAddress);  //This is Fine
    Console.WriteLine("{0}", user.Address.PostCode); /This is Fine


    foreach (MailingList ml in user.MailingLists) // this is 0
    {
       Console.WriteLine("{0}", ml.Name);
    }

我的模型如下:-

public class User : IEntityBase
    {
        public User()
        {
            MailingLists = new List<MailingList>();
        }

        public int Id { get; set; }
        public string Forename { get; set; }
        public string Surname { get; set; }
        public string EmailAddress { get; set; }
        public DateTime? DateLastUpdated { get; set; }
        public DateTime DateCreated { get; set; }
        public bool IsDeleted { get; set; }

        public virtual Address Address { get; set; }
        public ICollection<MailingList> MailingLists { get; set; }

    }

public class MailingList : IEntityBase
    {
        public MailingList()
        {
            Users = new List<User>();
        }

        public int Id { get; set; }
        public string Name { get; set; }
        public DateTime? DateLastUpdated { get; set; }
        public DateTime DateCreated { get; set; }
        public bool IsDeleted { get; set; }
        public ICollection<User> Users { get; set; } 
    }



public class Address : IEntityBase
    {
        public int Id { get; set; }
        public string AddressLine1 { get; set; }
        public string AddressLine2 { get; set; }
        public string AddressLine3 { get; set; }
        public string City { get; set; }
        public string County { get; set; }
        public string PostCode { get; set; }
        public DateTime? DateLastUpdated { get; set; }
        public DateTime DateCreated { get; set; }
        public bool IsDeleted { get; set; }
    }

欢迎提出任何建议。

【问题讨论】:

    标签: c#-4.0 ef-code-first entity-framework-5


    【解决方案1】:

    您既不急切地使用查询加载 MailingList 条目,也不满足延迟加载代理的要求,因此 EF 无法填充集合。

    要允许延迟加载,请将MailingList 属性更改为虚拟以允许 EF 代理覆盖它。

    要使用即时加载,请在查询中使用Include()System.Data.Entity 中的扩展方法)来指定应加载MailingList

    【讨论】:

    • 谢谢,这里的首选方法是什么?急切加载的扩展性是否较小?
    • 如果您确定需要这些数据,则急切加载会更好,因为它会在一次调用数据库中加载所有内容。如果您不知道需要什么数据,则延迟加载会更好。对于性能不是问题的情况,它也很方便。
    • 因此,如果我知道我在寻找什么,那么我可以在急切加载的基础上工作,因为我的调用只会从特定对象中得到我需要的东西。如果我需要抓取与实体相关的所有数据,延迟加载会拉取所有内容吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-02
    • 2012-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多