首页 > 解决方案 > 将 efCore 从 2.2 更新到 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 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;}
}

它是“拥有”的实体

public class Email
{
    public string Address { 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);
}

据我了解,我应该在 efcore3.1 中做的是将其更新为:

private static void ConfigureUser(EntityTypeBuilder<User> builder)
{
    builder.HasKey(s => s.Id);

    builder.Property(s => s.GuidId)
            .IsRequired();

    builder.OwnsOne(u => u.Email).WithOwner();
}

OnModelCreating()除了这个配置方法之外,该方法中的其他实体还有几个

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");
    }
}

异常将从builder.Entity(entityType.Name).Ignore("IsDirty")行中抛出。

就是这样。但是,这使差异为零,并且再次出现相同的错误。

我无法运行 add-migrations 来测试是否设置了其他东西,因为抛出了异常,我不确定如果我删除 ContextModelSnapshot 会发生什么......</p>

标签: entity-framework-coredomain-driven-designef-core-2.2ef-core-3.1

解决方案


感谢@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");
}

推荐阅读