繁体   English   中英

带有 OwnsMany 的 EF Core 迁移用于抽象 class

[英]EF Core Migrations with OwnsMany for abstract class

我在使用 EF Core 迁移方面有一些经验,并且还成功地使用.OwnsMany() 在这种情况下,我无法为我的 model 进行工作迁移。

我所拥有的是:

public class Class1
{
    public string Id { get; set; }
    public List<OwnedBaseClass> SomeList { get; set; }
}

public abstract class OwnedBaseClass
{
    public string BaseProperty { get; set; }
}

public class AA : OwnedBaseClass
{
    public string AAProperty { get; set; }
}

public class BB : OwnedBaseClass
{
    public string BBProperty { get; set; }
}

如果在我的 DbContext 中我这样做:

public virtual DbSet<AA> AARecords { get; set; }
public virtual DbSet<BB> BBRecords { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
     modelBuilder.Entity<OwnedBaseClass>().HasNoKey();
}

然后我得到一个表“OwnedBaseClass”的迁移,其中有附加列“Discriminator”,它可以区分 AA 和 BB 类型的记录。

到目前为止,一切都很好。

我需要的是使用.OwnsMany()为 OnModelCreating 中的类型 OwnedBaseClass 迁移 Class1,如下所示:

public virtual DbSet<Class1> Class1Records { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Class1>(x =>
    {
        x.HasKey(a => a.Id);
        x.OwnsMany(a => a.SomeList);
    });
}

添加迁移时出现以下错误:

The corresponding CLR type for entity type 'OwnedBaseClass' cannot be instantiated, and there is no derived entity type in the model that corresponds to a concrete CLR type.

我似乎无法解决这个问题。 如果我为 AA 类型添加 DbSet(这似乎是错误的),我会收到错误消息:

The entity type 'AA' requires a primary key to be defined. If you intended to use a keyless entity type, call 'HasNoKey' in 'OnModelCreating

如果我再添加(更糟)

modelBuilder.Entity<AA>().HasNoKey();

我收到另一个错误:

'AA' cannot be configured as keyless because it is a derived type; the root type 'OwnedBaseClass' must be configured as keyless instead. 

所以这就是我被困的地方。 任何帮助将非常感激。

谢谢阅读。

不确定这是否仍然相关但遇到了同样的问题。 这是自有类型的一个已知缺点

目前的不足

拥有的实体类型不能有 inheritance 个层次结构

我最终将它们配置为带有HasMany的普通相关对象。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM