如何使用与实体框架和SQL Server code-先迁移时创建一个聚集索引 [英] How to create a clustered index when using code-first migration with Entity Framework and SQL Server

查看:181
本文介绍了如何使用与实体框架和SQL Server code-先迁移时创建一个聚集索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 MessageModel 与创建消息时的时间戳属性。我想就这个长期属性的聚集索引。我希望做一个查询时,得到超过一定时间戳更新所有信息,实现查询加速。时间戳创造价值后,从来没有改变过。我现在有一个INT 编号属性普通索引。

I have a MessageModel with a timestamp attribute of when the message was created. I would like to make a clustered index on this long attribute. I hope to achieve a query speed-up when doing a query to get all messages newer than a certain timestamp. The timestamp value is never changed after creation. I currently have a regular index on a int Id attribute.

如何在ASP.NET一个模型添加一个聚集索引属性使用实体框架code-第一次迁移MVC 4.5?

How can I add a clustered index on a models attribute using Entity Framework code-first migration in ASP.NET MVC 4.5?

推荐答案

更新:的EntityFramework 6.1引入了 [索引] 属性,它可以是用于在任意字段中指定索引。例如:

UPDATE: EntityFramework 6.1 introduced the [Index] attribute which can be used to specify an index on an arbitrary field. Example:

public class MessageModel 
{
    [Index(IsClustered = true, IsUnique = false)]
    public long Timestamp { get; set; }
}

对于旧版本的实体框架,我将离开我的下面原来的答复:

For older versions of Entity Framework, I will leave my original answer below:

不幸的是EF 并没有真正提供多少支持索引的。接近这一点的最好方法取决于你在做迁移的类型。如果你不使用自动迁移和要添加索引到一个新的表(即你有一个迁移的),那么你可以修改生成的CREATETABLE语句迁移到添加索引。这种技术被用于实体框架教程之一(搜索索引找到它)

Unfortunately EF doesn't really provide much support for indexes. The best way to approach this depends on the type of migrations you're doing. If you're not using automatic migrations and you want to add an index to a NEW table (i.e. one you have a migration for), then you can modify the generated CreateTable statement in the migration to add indexes. This technique is used in one of the Entity Framework tutorials (search for Index to find it)

如果您的的使用自动迁移(或表​​已存在),那么你仍然可以使用旧式SQL创建索引 - 生成迁移,然后修改code,包括一个普通的旧式 CREATE INDEX 语句。

If you are using automatic migrations (or the table already exists) then you can still use old-style SQL to create your index - generate a migration, then modify your code to include a plain old CREATE INDEX statement.

这篇关于如何使用与实体框架和SQL Server code-先迁移时创建一个聚集索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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