Generate a composite unique constraint/index with owned entity, in EF Core

我只是一个虾纸丫 提交于 2019-12-20 02:57:05

问题


I have an entity that owns another entity

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

and I need to create an index on Entity1.Property and Entity2.Test. The configuration is like this

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

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

I tried both of the above code but they do not work. The first says

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

and the second one says:

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.

Can this be achieved without modifying the migration manually?


回答1:


Apparently EF Core doesn't support this feature yet.

See this issue on GitHub: https://github.com/aspnet/EntityFrameworkCore/issues/11336

There is also a workaround offered, which I have not tested myself.



来源:https://stackoverflow.com/questions/51724974/generate-a-composite-unique-constraint-index-with-owned-entity-in-ef-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!