实体框架一对多关系映射foreignkey导致导航属性为null

时间:2016-03-21 17:20:35

标签: c# sql-server entity-framework ef-code-first foreign-keys

我想尝试建立关系,同时想要指定子和父表外键以及导航属性,模型看起来像这样

public class Parent
{
    public Parent()
    {
        this.Childern = new HashSet<Child>();
    }
    public Guid Id { get; set; }

    public string Name { get; set; }

    //public Guid Child_Id { get; set; } 

    public ICollection<Child> Childern { get; set; }
}

public class Child
{
    public Child()
    {
        this.Parent = new Parent();
    }
    public Guid Id { get; set; }

    public string Name { get; set; }

    public Guid Parent_Id { get; set; }
    public Parent Parent { get; set; }
}

当我构建和运行项目时,只有上面的模型,我在导航属性上得到预期的结果,因为导航属性填充了预期的数据。 但我在数据库中获得了另外的不需要的列,如下所示

Id
Name
Parent_Id
Parent_Id1 (FK)

我在OnModelCreating中进一步配置了关系,如下所示

    modelBuilder.Entity<Child>()
    .HasRequired(p => p.Parent)
    .WithMany(p => p.Childern)
    .HasForeignKey(k => k.Parent_Id);

这次我在表格结构上获得了理想的结果,现在表格看起来像这样

Id
Name
Parent_Id (FK)

但我在导航属性上显示为空,请注意我尝试急切加载

    public static void TestParent()
    {
        using (var context = new ILDBContext())
        {
            var parents = context.Parents
                .Include(p => p.Childern)
                .ToList();

            foreach (var parent in parents)
            {
                Console.WriteLine("Parent: {0} Childern: {1}", parent.Name, parent.Childern.Count());
                foreach (var child in parent.Childern)
                {
                    Console.WriteLine("Child: {0}", child.Name);
                }
            }
        }
    }

此外,如果有人可以建议如何在两个模型中使用FK(如Parent_Id和Child_Id),我会感谢如何配置关系 感谢。

1 个答案:

答案 0 :(得分:1)

您需要删除Parent构造函数中的Child作业:

public Child()
{
    this.Parent = new Parent();
}

必须是

public Child() {} 

或者根本没有定义它。对于ICollection<Child>中的Parent,它并没有真正有所作为。

相关问题