Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF can you make a Mutli-column Index using shadow properties?

I'm trying to create a multi-column unique index using a shadow property. I know I can solve this problem with just adding a property, but I would like to see if this is possible in a way to keep my model clean.

To create a multi-column index you have the following option in Fluent API:

modelBuilder.Entity<AlbumTrack>().HasIndex(t => new { t.TrackNumber, t.AlbumId).IsUnique();

But I don't want to clutter my model with an extra AlbumId property and thus would like to use a shadow property, for a single column this works as followed:

modelBuilder.Entity<AlbumTrack>().HasIndex(t => EF.Property<int>(t,"AlbumId")).IsUnique();

I tried the following:

modelBuilder.Entity<AlbumTrack>()
    .HasIndex(t => new { t.TrackNumber, EF.Property<int>(t,"AlbumId")})
    .IsUnique();

However my IDE throws the following error:

Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access.

Anybody has an idea how to do this with using a shadow properties or is this just not possible?

edit: various grammar arrors.

like image 385
N. Janné Avatar asked Dec 12 '17 20:12

N. Janné


People also ask

What does shadow property do?

Shadow properties are most often used for foreign key properties, where the relationship between two entities is represented by a foreign key value in the database, but the relationship is managed on the entity types using navigation properties between the entity types.

Does Entity Framework have index core?

The Entity Framework Core Fluent API HasIndex method is used to create a database index on the column mapped to the specified entity property. By default, indexes are created for foreign keys and alternate keys.

How do I create an index in EF core?

Add an index with a single column The simplest way to add an index is to by adding the [Index] attribute on the model class and specifying which columns should be included in the index.

Which method is used to apply configuration to entities or their properties in the Entity Framework Core?

Property Mapping. The Property method is used to configure attributes for each property belonging to an entity or complex type.


1 Answers

It's possible. You can simply use the HasIndex overload with params string[] propertyNames.

First make sure the shadow property is defined:

modelBuilder.Entity<AlbumTrack>()
    .Property<int>("AlbumId");

and then define the index:

modelBuilder.Entity<AlbumTrack>()
    .HasIndex("TrackNumber", "AlbumId")
    .IsUnique();
like image 129
Ivan Stoev Avatar answered Oct 09 '22 12:10

Ivan Stoev