如何使用代码优先在Entity Framework 6.2中创建索引 [英] How to create index in Entity Framework 6.2 with code first

查看:113
本文介绍了如何使用代码优先在Entity Framework 6.2中创建索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法使用代码优先在属性/列上创建索引,而不是使用新的 IndexAttribute

Is there a way to create an index on a property/column using code-first, instead of using the new IndexAttribute ?

推荐答案

目前,没有一流支持创建通过流畅的API指定一个索引,但是您可以通过流畅的API将属性标记为具有注释API的属性。这将允许您通过流畅的界面添加索引属性。

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.

以下是工作项的一些示例从EF的问题网站。

Here are some examples from the work item from Issues site for EF.

在单个列上创建索引:

modelBuilder.Entity<MyEntity>()
    .Property(e => e.MyProperty)
    .HasColumnAnnotation(
        IndexAnnotation.AnnotationName, 
        new IndexAnnotation(new IndexAttribute()));

单列上的多个索引:

modelBuilder.Entity<MyEntity>()
    .Property(e => e.MyProperty)
    .HasColumnAnnotation(
        IndexAnnotation.AnnotationName, 
        new IndexAnnotation(new[]
            {
                new IndexAttribute("Index1"),
                new IndexAttribute("Index2") { IsUnique = true }
            }));

多列索引:

modelBuilder.Entity<MyEntity>()
    .Property(e => e.MyProperty1)
    .HasColumnAnnotation(
        IndexAnnotation.AnnotationName,
        new IndexAnnotation(new IndexAttribute("MyIndex", 1)));

modelBuilder.Entity<MyEntity>()
    .Property(e => e.MyProperty2)
    .HasColumnAnnotation(
        IndexAnnotation.AnnotationName, 
        new IndexAnnotation(new IndexAttribute("MyIndex", 2)));

使用上述技术将导致 .CreateIndex()调用在您的 Up()函数中为您自动创建,当您支持下一次迁移(或者如果您不使用迁移,则自动在数据库中创建)。

Using the above techniques will cause .CreateIndex() calls to be automatically created for you in your Up() function when you scaffold your next migration (or be automatically created in the database if you are not using migrations).

这篇关于如何使用代码优先在Entity Framework 6.2中创建索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆