9

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.

N. Janné
  • 105
  • 6
  • 1
    Unfortunately even if you define a name (`.HasIndex(t => new { t.TrackNumber, AlbumId = EF.Property(t, "AlbumId") })` and avoid compilation error, you get runtime error *"The properties expression 't => new <>f__AnonymousType11`2(TrackNumber = t.TrackNumber, AlbumId = Property(t, "AlbumId"))' 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*". So the string overload from my answer is currently the only choice – Ivan Stoev Dec 12 '17 at 20:35

1 Answers1

11

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();
Ivan Stoev
  • 195,425
  • 15
  • 312
  • 343
  • 1
    Yes, it was that simple, thank you very much. The property method is without the has, like .Property, but not that anybodies IDE wouldn't catch that, thank you. – N. Janné Dec 12 '17 at 20:51