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

entity-framework-core

Question

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
2
8/7/2018 2:54:51 PM

Accepted Answer

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.

2
8/9/2018 12:16:09 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow