Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 775
Dan Avatar asked Oct 17 '22 14:10

Dan


1 Answers

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.

like image 157
Thomas Avatar answered Oct 21 '22 07:10

Thomas