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.
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.
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.
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.
Property Mapping. The Property method is used to configure attributes for each property belonging to an entity or complex type.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With