简体   繁体   English

EF7 一对多映射

[英]EF7 One-to-many mapping

I'm trying to map two classes using Entity Framework 7.0.0-rc1-final.我正在尝试使用实体框架 7.0.0-rc1-final 映射两个类。 Here's my classes:这是我的课程:

    public class ParentClass
    {
            public ParentClass() { }

            [Key]
            public Int32 Id { get; set; }

            [Required]
            public String Field { get; set; }

            public List<ChildClass> Children { get; set; }

    }

    public class ChildClass
    {
        [Key]
        public Int32 Id { get; set; }

        public Int32 ParentID { get; set; }

        public ParentClass Parent { get; set; }
    }

and I have a mapping code in my context class with Fluent API:我的上下文类中有一个带有 Fluent API 的映射代码:

    builder.Entity<ChildClass>().HasOne(x => x.Parent)
           .WithMany(x => x.Children).HasForeignKey(x => x.ParentID);

Then I add couple of ParentClass instances with children and save them to DB.然后我添加了几个带有孩子的 ParentClass 实例并将它们保存到数据库中。 They are saved to DB and look good in the DB, but when I'm trying to get list of ParentClass children I always have null list:它们被保存到数据库并在数据库中看起来不错,但是当我尝试获取 ParentClass 孩子的列表时,我总是有空列表:

var data = _context.ParentInstances.ToList();
data[any].Children == null

You need to declare the fact that you want to include the children in query Try:您需要声明要在查询中包含孩子的事实 Try:

var data = _context.ParentInstances.Include(p => p.Children).ToList();

Edit:编辑:

For make sure to add a reference to Microsoft.Data.Entity确保添加对 Microsoft.Data.Entity 的引用

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

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