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
有人可以帮忙吗?
答案 0 :(得分:0)
您想要的不能完全按照您想要的方式完成 - 当使用与所有者位于同一个表中的表拆分/拥有实体时,看起来EFCore要求相关实体不为空。
我认为有两个选项 - 共享主键(需要两个表和一个eager /显式加载来加载具有主体的依赖实体)或每个层次表(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();