在 EF Core 中生成具有所属实体的复合唯一约束/索引

2023-11-24

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

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.

是否可以在不手动修改迁移的情况下实现这一目标?


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

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

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 EF Core 中生成具有所属实体的复合唯一约束/索引 的相关文章

随机推荐