Is there a way to create an index on a property/column using code-first, instead of using the new IndexAttribute
?
相关问题
- Entity Framework Code First Migration
- Entity Framework throws exception - Network Relate
- Slow loading first page - ASP.NET MVC
- query and create objects with a one to many relati
- Entity Framework override default property convent
相关文章
-
EF6 DbSet
returns null in Moq - Entity Framework 4.3.1 failing to create (/open) a
- EF6 code first: How to load DbCompiledModel from E
- Why do I need a ToList() to avoid disposed context
- Code-First Add-Migration keeps adding the same col
- EF Codefirst validate unique property?
- EF Core 'another instance is already being tra
- Add XML documentation / comments to properties/fie
Well 26.10.2017 Entity Framework 6.2 was officially released. It includes a possibility to define indexes with ease via Fluent API. Ho it is to use was already announced in the beta of 6.2.
Now you can use the
HasIndex()
method, followed byIsUnique()
if it should be an unique index.Just a small comparison (before/after) example:
It is also possible to mark the index as clustered with
.IsClustered()
.EDIT #1
Added an example for multi column index and additional information how to mark an index as clustered.
EDIT #2
As additional information, in EF Core 2.1 it is exactly the same like in EF 6.2 now.
Here is the MS Doc artcile as reference.
From EF 6.1 onward the attribute
[Index]
is supported.Use
[Index(IsUnique = true)]
for unique index.Here is the link from Microsoft
Currently there is no "first class support" for creating a index via the fluent API, but what you can do is via the fluent API you can mark properties as having attributes from the Annotation API. This will allow you to add the
Index
attribute via a fluent interface.Here are some examples from the work item from Issues site for EF.
Create a index on a single column:
Multiple indexes on a single column:
Multi-Column indexes:
Using the above techniques will cause
.CreateIndex()
calls to be automatically created for you in yourUp()
function when you scaffold your next migration (or be automatically created in the database if you are not using migrations).You can use the INDEX data annotaion Code First Data Annotations
I write an extension method for use in fluent EF to avoid extra code:
then use it like this:
or like this if index needs some configs:
Without an explicit name:
With a specific name: