[英]How to map two classes to one table in 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();
}
}
我可以映射到一个看起来像这样的表吗?
| 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要求相关实体不为null。
我认为有两个选项-共享主键(需要两个表,并且需要一个紧急/显式负载才能用主体加载从属实体)或按层次结构表(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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.