有没有办法使用代码优先而不是使用新的IndexAttribute
在属性/列上创建索引?
发布于 2014-03-25 03:31:25
目前还没有用于通过fluent API创建索引的"first class support",但是您可以通过fluent API将属性标记为具有来自Annotation API的属性。这将允许您通过fluent接口添加Index
属性。
以下是来自EF的Issues站点的工作项的一些示例。
在单个列上创建索引:
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)));
使用上述技术将导致在构建下一次迁移的脚手架时,在Up()
函数中自动创建.CreateIndex()
调用(如果不使用迁移,则会在数据库中自动创建)。
发布于 2015-03-22 11:57:58
我已经创建了一些扩展方法,并将它们包装在nuget包中,以使这变得更容易。
安装EntityFramework.IndexingExtensions
nuget包。
然后,您可以执行以下操作:
public class MyDataContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Customer>()
.HasIndex("IX_Customers_Name", // Provide the index name.
e => e.Property(x => x.LastName), // Specify at least one column.
e => e.Property(x => x.FirstName)) // Multiple columns as desired.
.HasIndex("IX_Customers_EmailAddress", // Supports fluent chaining for more indexes.
IndexOptions.Unique, // Supports flags for unique and clustered.
e => e.Property(x => x.EmailAddress));
}
}
发布于 2016-05-02 22:19:46
如果没有明确的名称:
[Index]
public int Rating { get; set; }
使用特定的名称:
[Index("PostRatingIndex")]
public int Rating { get; set; }
https://stackoverflow.com/questions/22618237
复制相似问题