【发布时间】:2020-05-03 11:36:04
【问题描述】:
我正在尝试在 EF Core 中实现自引用关系。 我正在尝试使用未映射到真实数据库列的自定义外键和主键。
使用下面的代码,我得到了错误
'找不到实体类型'Person'的属性'HeadOfHouseholdForeignKey'的支持字段,并且该属性没有设置器
有没有办法让这些外键/主键没有映射到数据库中的列? 有没有办法在 EF Core 中做得很好?
例子:
PersonContext.cs
using Microsoft.EntityFrameworkCore;
namespace ConsoleApp1
{
public class PersonContext : DbContext
{
DbSet<Person> People;
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<Person>()
.HasOne(p => p.HeadOfHouseHold)
.WithMany()
.HasForeignKey(p => p.HeadOfHouseholdForeignKey)
.HasPrincipalKey(p => p.HeadOfHouseholdPrincipalKey);
}
}
}
Person.cs
namespace ConsoleApp1
{
internal class Person
{
public int PersonId { get; set; }
public string Name { get; set; }
public string FamilyName { get; set; }
public string PersonSequenceNumber { get; set; }
public Person HeadOfHouseHold { get; set; }
public string HeadOfHouseholdForeignKey
{
get
{
// Head of household always has '01' as PersonSequenceNumber in DB, other members increment from 01 to 02, 03, etc
if (PersonSequenceNumber != "01")
{
return FamilyName + "01";
}
else
{
return null;
}
}
}
public string HeadOfHouseholdPrincipalKey
{
get
{
return FamilyName + PersonSequenceNumber;
}
}
}
}
【问题讨论】:
-
外键是一个数据库概念。你想通过只有“外键”的代码模型来实现什么?
-
我希望能够使用 EF Core .Include() 方法来简化获取相关数据的过程
-
你想要什么表。Include()?也许是人?
-
相关表的键是什么样的?它们像“Tom01”吗?
-
类似
People.Include(p => p.HeadOfHousehold)。我想使用复合键 { FamilyName, PersonSequenceNumber } 包含来自同一个表的记录(因此是自引用的)。例如,Jones01 是爸爸,Jones02 是妈妈,等等
标签: c# entity-framework entity-framework-core