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

╄→гoц情女王★ 提交于 2020-05-23 12:24:06

问题


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.


回答1:


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();


来源:https://stackoverflow.com/questions/47780852/ef-can-you-make-a-mutli-column-index-using-shadow-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!