在将ef-core从2.1版升级到2.2版(2.2.2)之后,我在进行迁移时开始出现错误。 我创建了一个测试项目,这是我的代码:
public class Root
{
public int Id { get; set; }
public MainAddress Address1 { get; set; }
public MainAddress Address2 { get; set; }
}
public class MainAddress
{
public int Id { get; set; }
public string Name { get; set; }
public SubAddress SubAddress { get; set; }
}
public class SubAddress
{
public int Id { get; set; }
public string Name { get; set; }
public int Number { get; set; }
public SubSubAddress SubSubAddress { get; set; }
}
public class SubSubAddress
{
public int Id { get; set; }
public string Text { get; set; }
}
public class RootConfig : IEntityTypeConfiguration<Root>
{
public void Configure(EntityTypeBuilder<Root> builder)
{
builder.ToTable("Roots");
builder.HasKey(it => it.Id);
builder.OwnsOne(root => root.Address1, address =>
{
address.OwnsOne(a => a.SubAddress, subAddress =>
{
subAddress.OwnsOne(it => it.SubSubAddress);
});
});
builder.OwnsOne(root => root.Address2, address =>
{
address.OwnsOne(a => a.SubAddress, subAddress =>
{
subAddress.OwnsOne(it => it.SubSubAddress);
});
});
}
}
public class TestContext : DbContext
{
public TestContext(DbContextOptions<TestContext> context) : base(context)
{
}
public DbSet<Root> Roots { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.ApplyConfiguration(new RootConfig());
}
}
因此,当我更新数据库时出现错误: System.InvalidOperationException:无法将实体类型'EFError1.Models.SubAddress'添加到模型中,因为已经存在具有相同名称的弱实体类型。
如果我使用OwnsOne嵌套2次-那么一切都很好。 有想法吗?