如何将两个类映射到EF Core中的一个表中
问题描述:
public class User
{
public Account Account { get; set; }
public string SomeInfo { get; set; }
public Guid Id { get; set; }
}
public class Account
{
public string Name { get; set; }
}
public class UserEntityTypeConfiguration : IEntityTypeConfiguration<User>
{
public virtual void Configure(EntityTypeBuilder<User> builder)
{
builder.HasKey(x => x.Id);
builder
.Property(t => t.Id)
.ValueGeneratedOnAdd();
}
}
我可以映射到一张看起来像这样的表吗?如何将两个类映射到EF Core中的一个表中
| Id | SomeInfo | AccountName |
-------------------------------
| 1 | info1 | name1 |
| 2 | info2 | NULL |
和映射后,1将映射到:
User.SomeInfo is "info1"
User.Account is not null
User.Account.Name is "name1"
和加载2会导致
User.SomeInfo is "info2"
User.Account is null
谁能帮助?
答
你想要的东西不能按照你想要的方式完成 - 当使用与所有者位于同一个表中的表拆分/所有实体时,它看起来像EFCore要求相关实体不为空。
我觉得有两个选项 - 共享主键(这将需要两个表和一个急需/显式负载加载与委托人的依赖实体)或逐层次表(TPH)继承(这将需要两个实体类型)。
共享主键:
public class SharedKeyPrincipal
{
public int Id { get; set; }
public int PrincipalProperty { get; set; }
public SharedKeyDependent Dependent { get; set; }
}
public class SharedKeyDependent
{
public int Id { get; set; }
public int DependentProperty { get; set; }
public SharedKeyPrincipal Principal { get; set; }
}
modelBuilder.Entity<SharedKeyDependent>()
.HasOne(d => d.Principal)
.WithOne(p => p.Dependent)
.IsRequired()
.HasForeignKey<SharedKeyDependent>(d => d.Id);
var principals = dbContext.Set<SharedKeyPrincipal>()
.Include(p => p.Dependent)
.ToArray();
TPH:
public class InheritanceBaseEntity
{
public int Id { get; set; }
public int BaseEntityProperty { get; set; }
}
public class InheritanceDerivedEntity : InheritanceBaseEntity
{
public int DerivedEntityProperty { get; set; }
}
public DbSet<InheritanceBaseEntity> InheritanceBaseEntities { get; set; }
public DbSet<InheritanceDerivedEntity> InheritanceDerivedEntities { get; set; }
// use .OfType<InheritanceDerivedEntity>() to get entities that have a
// non-null 'value' for the related properties
var inheritanceEntities = dbContext.Set<InheritanceBaseEntity>().ToArray();
+0
感谢您的回答。在第一个示例中,它设置了一对一的关系,我希望帐户为空。我似乎无法在EF核心中设置可选的一对一关系:( – chris31389
+0
'SharedKeyDependent'在这种情况下是'Account'并且可以为空 – Moho
你似乎在问[**国有类型**](https://docs.microsoft.com/en-我们/ EF /核心/什么,是全新/)。或**表拆分**从相同的链接。 –
我觉得这更近一步,但它仍然使用一对一的关系。我希望能够说,如果AccountName == null,那么不会生成一个Account对象 – chris31389