Entity framework core 将efCore从2.2更新到3.1时拥有的实体
我正在将一个基于DDD设计原则的现有项目从efcore 2.2迁移到efcore 3.1。数据库设置基于Julie Lerman几年前写的一系列文章 一般来说,这很好,但我很难解决与自有实体一起发布的问题,尤其是以下错误消息:Entity framework core 将efCore从2.2更新到3.1时拥有的实体,entity-framework-core,domain-driven-design,ef-core-2.2,ef-core-3.1,Entity Framework Core,Domain Driven Design,Ef Core 2.2,Ef Core 3.1,我正在将一个基于DDD设计原则的现有项目从efcore 2.2迁移到efcore 3.1。数据库设置基于Julie Lerman几年前写的一系列文章 一般来说,这很好,但我很难解决与自有实体一起发布的问题,尤其是以下错误消息: InvalidOperationException: The type 'ApplicationCore.Entities.UserAggregate.Email' cannot be configured as non-owned because an owned en
InvalidOperationException: The type 'ApplicationCore.Entities.UserAggregate.Email' cannot be configured as non-owned because an owned entity type with the same name already exists
这两个实体是:
public class User
{
public int Id { get; private set; }
public Guid GuidId { get; private set; }
public Email Email {get; private set;}
}
它是一个“拥有”的实体
以前在EfCore 2.2中,配置为:
private static void ConfigureUser(EntityTypeBuilder<User> builder)
{
builder.HasKey(s => s.Id);
builder.Property(s => s.GuidId)
.IsRequired();
builder.OwnsOne(u => u.Email);
}
异常将从builder.Entity(entityType.Name).Ignore(“IsDirty”)
行引发
就这样。但是,这将产生零差异,并且相同的错误再次出现
我无法运行添加迁移来测试是否有其他设置,因为引发了异常,我不确定如果删除ContextModelSnapshot会发生什么…谢谢@IvanStoev,请参阅他在评论中链接的问题 配置是正确的,我的问题是在尝试删除Shadow属性时出现的
// Remove shadow property for entities which are not owned
foreach (var entityType in builder.Model.GetEntityTypes().Where(e => !e.IsOwned()))
{
builder.Entity(entityType.Name).Ignore("IsDirty");
}
在此处未显示的代码中,您有
modelBuilder.Entity()
调用Email
type as参数/泛型类型参数。您可以尝试在VS debugger中运行一个简单的查询,如抛出break on exception的情况下运行context.Users.ToLIst()
,并查看生成异常的确切行。啊,因此在我的OnModelCreating()
方法中,有所有的配置方法,然后它遍历build.Model中的所有实体以删除不需要的属性。我将更新这个问题,使这一部分更加明确。您可能需要使用IsOwned()
排除实体类型-请参阅Genius!就是这个:-)我会加上这个作为回答,干杯。昨天我一直在过滤类型本身的名称以排除它们;但可能还有其他配置问题。
private static void ConfigureUser(EntityTypeBuilder<User> builder)
{
builder.HasKey(s => s.Id);
builder.Property(s => s.GuidId)
.IsRequired();
builder.OwnsOne(u => u.Email).WithOwner();
}
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<ForecastSetup>(ConfigureForecastSetup);
…
builder.Entity<User>(ConfigureUser);
// Remove internal property
foreach (var entityType in builder.Model.GetEntityTypes())
{
builder.Entity(entityType.Name).Ignore("IsDirty");
}
}
// Remove shadow property for entities which are not owned
foreach (var entityType in builder.Model.GetEntityTypes().Where(e => !e.IsOwned()))
{
builder.Entity(entityType.Name).Ignore("IsDirty");
}