EF 6.1 Unique Nullable Index

后端 未结 4 1463
Happy的楠姐
Happy的楠姐 2020-12-01 07:23

In EF 6.1 using Code First you can create Indexes using Attributes in your Entities or using the fluent API along the lines of:

 Property(x => x.PropertyN         


        
4条回答
  •  余生分开走
    2020-12-01 08:03

    No, you cannot natively do it.

    But I created a custom SQL generator that enables the following:

    1. Sort the columns in your index ASC or DESC
    2. Enable the use of the WHERE keyword

    To be able to use it, you must tweak your index name only. The name is separated in 3 parts by :. The parts are:

    1. Index name
    2. Sort orders
    3. Where clause

    If you have an index on 2 columns, need Column1 to be sorted ASC and Column2 DESC, and need a where clause, your index name would be:

    var uniqueName = "UN_MyIndex:ASC,DESC:Column1 IS NOT NULL";
    

    And you simply use it like this:

    Property(t => t.Column1)
                .HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute(uniqueName) { IsUnique = true, Order = 1 }));
    
    Property(t => t.Column2)
                .HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute(uniqueName) { IsUnique = true, Order = 2 }));
    

    Then, in your Configuration.cs file, add this line in your constructor:

    SetSqlGenerator("System.Data.SqlClient", new CustomSqlServerMigrationSqlGenerator());
    

    Finally, create the CustomSqlServerMigrationSqlGenerator.cs file as shown: code here.

提交回复
热议问题