我有以下课程
public class Parent
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Child> Children{ get; set; }
}
public class Child
{
public int Id { get; set; }
public string Name { get; set; }
public int ParentId { get; set; }
public virtual Parent Parent { get; set; }
}
我尝试在这里简化我的类结构。两个类都有不同的属性,所以我真的需要有两个不同的类/类型
我希望将此数据存储在具有以下结构的平面/单个数据库表中
ParentId - 家长姓名 - ChildId - 孩子姓名
我尝试了多种流畅配置的组合,但无法以这种方式生成表格。
当我从数据库取回数据时,我仍然需要链接两个实体。
请注意,我使用的是 EF Core 3.1,因此此版本尚不支持 ComplexType。
无需额外的映射表即可实现此目的。您将需要同一类中的
one-to-many
的反向属性。那你就得用FuentApi
public class Class
{
public int Id { get; set; }
public string Name { get; set; }
//reverce property
public int ParentId { get; set; }
public Class Parent { get; set; }
public virtual ICollection<Class> Children { get; set; }
}
配置
builder.Entity<Class>()
.HasOne(e => e.Parent)
.WithMany(e => e.Children )
.HasForeignKey(e => e.ParentId);