Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Filter Index

I use EF 6.1.x Code First.

I have read that an Index with Filter Expression is not supported by EF latest.

There is also no solution on SO:

EF 6.1 Unique Nullable Index

One year later, what is the working way to make a Filter Index work with Code First and DbMigrations?

CREATE UNIQUE NONCLUSTERED INDEX [IX_DefaultLanguageApplicationId] ON [dbo].[Languages]
(
    [IsDefaultLanguage] ASC,
    [ApplicationId] ASC,
)
WHERE ([IsDefaultLanguage]=(1))
like image 643
Elisabeth Avatar asked Oct 01 '15 18:10

Elisabeth


People also ask

Does Entity Framework use indexes?

Indexing is the new feature in entity framework where you can improve the performance of your Code First application by reducing the time required to query data from the database.

How do I filter data in Entity Framework?

To filter data, use linq. You can not use Filter property of BindingSource when the underlying list is BindingList<T> ; Only underlying lists that implement the IBindingListView interface support filtering. To remove filter, just set the data source of your binding source to the local storage of your entities again.

What is an index filter?

A filtered index is an optimized disk-based rowstore nonclustered index especially suited to cover queries that select from a well-defined subset of data. It uses a filter predicate to index a portion of rows in the table.

Does fluent API have index?

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.


2 Answers

In EF 6.1, the working way to make the this work with Code First and DbMigrations is to use the Sql method in the DbMigration class:

public partial class AddIndexes : DbMigration
{
    public override void Up()
    {
        Sql(@"CREATE UNIQUE NONCLUSTERED INDEX
             [IX_DefaultLanguageApplicationId] ON [dbo].[Languages]
             (
                [IsDefaultLanguage] ASC,
                [ApplicationId] ASC 
             )
             WHERE ([IsDefaultLanguage]=(1))");

    }

    public override void Down()
    {
        DropIndex("dbo.Languages", "IX_DefaultLanguageApplicationId");
    }
}

But I realise that you are probably asking if you can create an index using the IndexAttribute introduced in 6.1, but with an Filter - the answer to that is "No"

Almost a duplicate of: Entity Framework 6.1 - Create index with INCLUDE statement

like image 78
Colin Avatar answered Oct 12 '22 00:10

Colin


Please note that right now EF core 2.1.X added built in support for filtered indexes via the HasFilter extension on the IndexBuilder, so a custom implementation is not required anymore.

See this for more details

like image 9
ilmax Avatar answered Oct 12 '22 02:10

ilmax