Entity Framework 一对多关系映射外键导致导航属性为空
Entity Framework One To Many Relationship mapping foreignkey causing null on navigation properties
我正在尝试建立关系,同时想要指定子和父 table 的外键以及导航 属性,模型看起来像这样
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);
这次我在 table 结构上得到了想要的结果,现在 table 看起来像这样
Id
Name
Parent_Id (FK)
但是我的导航属性为空,请注意我正在尝试 Eagerly Loading
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);
}
}
}
}
此外,如果有人可以建议我应该如何配置关系,如果我在 Parent_Id 和 Child_Id 等两个模型中都需要 FK,我将不胜感激
谢谢。
您需要删除 Child
构造函数中的 Parent
赋值:
public Child()
{
this.Parent = new Parent();
}
必须
public Child() {}
或者你根本不定义它。对于 Parent
中的 ICollection<Child>
,这并没有什么区别。
我正在尝试建立关系,同时想要指定子和父 table 的外键以及导航 属性,模型看起来像这样
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);
这次我在 table 结构上得到了想要的结果,现在 table 看起来像这样
Id Name Parent_Id (FK)
但是我的导航属性为空,请注意我正在尝试 Eagerly Loading
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);
}
}
}
}
此外,如果有人可以建议我应该如何配置关系,如果我在 Parent_Id 和 Child_Id 等两个模型中都需要 FK,我将不胜感激 谢谢。
您需要删除 Child
构造函数中的 Parent
赋值:
public Child()
{
this.Parent = new Parent();
}
必须
public Child() {}
或者你根本不定义它。对于 Parent
中的 ICollection<Child>
,这并没有什么区别。