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

c# ef-fluent-api entity-framework entity-framework-core sqlite

Question

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 propertie, but i would like to see if this is possible without doing that 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 dont want to clutter my model with an extra AlbumId property and thus wanna use a shadow property, for a single column this works:

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

But for a multi-column index using a shadow propertie, like following

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

I get the following error in vscode

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 it just not possible?

1
7
12/12/2017 8:45:29 PM

Accepted Answer

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();
8
12/12/2017 11:42:51 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