0
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

任何人都可以帮忙吗?

4

1 回答 1

0

您想要的不能完全按照您想要的方式完成 - 当使用与所有者位于同一表中的表拆分/拥有的实体时,看起来 EFCore 要求相关实体不能为空。

我认为有两个选项 - 共享主键(需要两个表和一个急切/显式加载来加载具有主体的依赖实体)或 Table-per-Hierarchy (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();

总产值:

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();
于 2017-10-04T16:53:39.300 回答