【问题标题】:Generate a composite unique constraint/index with owned entity, in EF Core在 EF Core 中生成具有自有实体的复合唯一约束/索引
【发布时间】:2018-08-07 10:49:44
【问题描述】:

我有一个拥有另一个实体的实体

public class Entity1
{
  [Key]
  [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
  public virtual int ID { get; set; }

  public string Property { get; set; }

  public Entity2 Description { get; set; }
}

public class Entity2
{
   public string Test { get; set; }
}

我需要在 Entity1.Property 和 Entity2.Test 上创建一个索引。配置是这样的

builder.OwnsOne(pt => pt.Description);

builder.HasIndex(p => new { p.Property, p.Description.Test }).IsUnique();
//builder.HasIndex("Property", "Description_Test").IsUnique();

我尝试了上述两个代码,但它们都不起作用。第一个说

The properties expression 'p => new <>f__AnonymousType3`7(Property = p.DeviceClassId, 
Test = p.Description.Test)' is not valid. The expression should represent a property 
access: 't => t.MyProperty'. When specifying multiple properties use an anonymous type:
't => new { t.MyProperty1, t.MyProperty2 }'.
Parameter name: propertyAccessExpression

第二个说:

The property 'Description_test' cannot be added to the type 'Entity1' because there was no 
property type specified and there is no corresponding CLR property or field. To add a 
shadow state property the property type must be specified.

不手动修改迁移可以实现吗?

【问题讨论】:

    标签: entity-framework-core


    【解决方案1】:

    显然 EF Core 还不支持此功能。

    在 GitHub 上查看此问题: https://github.com/aspnet/EntityFrameworkCore/issues/11336

    还提供了一种解决方法,我自己没有测试过。

    【讨论】:

      【解决方案2】:

      为我解决的解决方法是在迁移目录中删除自动生成的文件DataContextModelSnapshot.cs 并再次运行它重新生成的迁移,迁移文件中已经引用了一些数据库,这些数据库刚刚删除并完成... 可能不是最优雅的解决方案,但它确实有效。


      仅供参考,EF Core 6.0 发生过两次。

      【讨论】:

        猜你喜欢
        • 2017-04-07
        • 1970-01-01
        • 2017-03-20
        • 2021-06-24
        • 2017-10-31
        • 1970-01-01
        • 2019-10-26
        • 2021-09-13
        • 2014-11-28
        相关资源
        最近更新 更多