Entity Framework 6.1(代码优先)增加了通过 IndexAttribute
添加索引的可能性。 .该属性采用一个参数来指定索引是聚簇的还是非聚簇的。
同时,据我所知, Entity Framework 要求每个实体都有一个主键(用 KeyAttribute
注释),并且该主键始终创建为集群键。 p>
因此,一旦我申请 IndexAttribute
与 IsClustered = true
,我得到一个错误,因为,由于键,已经有 一个聚集索引。
那么,如何使用 IndexAttribute
创建一个不是主键的聚簇索引? ?是 IsClustered
IndexAttribute
的属性(property)可以用吗?
(关于更多上下文:我正在映射一个仅用于通过 LINQ 查询读取的表。我不需要实际插入、更新或删除该表中的实体。因此,我不需要一个主键。理想情况下,我想要一个没有主键的表,但有一个非唯一的、针对读取进行了优化的聚簇索引。)
编辑 (2014-04-11):另见 https://entityframework.codeplex.com/workitem/2212 .
最佳答案
一张表上只能有一个聚簇索引,默认情况下 Entity Framework/Sql Server 将它放在主键上。
那么 IsClustered
属性在不是主键的索引上有什么用呢?好问题! (+1)
这个类:
public class Blog
{
[Key()]
public int Id { get; set; }
[MaxLength(256)]//Need to limit size of column for clustered indexes
public string Title { get; set; }
[Index("IdAndRating", IsClustered = true)]
public int Rating { get; set; }
}
将生成此迁移:
public override void Up()
{
CreateTable(
"dbo.Blogs",
c => new
{
Id = c.Int(nullable: false, identity: true),
Title = c.String(maxLength: 256),
Rating = c.Int(nullable: false),
});
.PrimaryKey(t => t.Id)
.Index(t => t.Rating, clustered: true, name: "IdAndRating");
}
将迁移更改为:
public override void Up()
{
CreateTable(
"dbo.Blogs",
c => new
{
Id = c.Int(nullable: false, identity: true),
Title = c.String(maxLength: 256),
Rating = c.Int(nullable: false),
});
CreateIndex("dbo.Blogs",
new[] { "Rating", "Title" },
clustered: true,
name: "IdAndRating");
}
这应该创建没有主键但在其他列上有聚集索引的表
编辑 在您不需要插入、更新或删除数据的情况下,您不需要一个完整的实体,您可以使用 raw sql queries填充类。您需要将自己的 sql 添加到迁移中以创建表,因为 EF 不会自动执行它,但这意味着您可以根据需要创建表和索引。
关于c# - 在 Entity Framework 6.1(非 Core)中,如何使用 IndexAttribute 来定义聚簇索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22813137/