[英]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.