如何在不获取SqlExceptions的情况下使用Entity Framework 6.1中的IndexAttribute添加列索引?

时间:2015-01-19 04:20:57

标签: c# mysql sql-server database entity-framework

我使用Entity Framework 6.1代码优先方法来创建我的数据库架构。它已经好几个月了,但随着数据库的使用越来越多,我已经确定我需要在几个列上添加索引以在几种情况下提高查询性能。

对不起,这有点长的解释,我不知道哪些步骤(如果有的话)与我现在看到的错误有关...

首先,我开始使用这样的现有属性:

[Required]
public string LocationId { get; set; }

在我的第一次尝试中,我尝试过简单地添加IndexAttribute:

[Index]
[Required]
public string LocationId { get; set; }

我尝试直接运行,因为我启用了自动迁移,但在我启动并运行并查看数据库之后,没有添加任何索引,因此我执行了Add-Migration - >更新 - 数据库舞蹈。

更新 - 数据库失败:

System.Data.SqlClient.SqlException (0x80131904): Column 'LocationId'
in table 'dbo.Deliveries' is of a type that is invalid for use as a
key column in an index.

所以我还原了我的所有代码,添加了[MaxLength(128)]属性,因为我的ID是GUID,并且重新添加 - 迁移 - >更新数据库。

[MaxLength(128)]
[Required]
public string LocationId { get; set; }

这次我遇到了此线程中描述的错误,因为EF为我的列添加了默认约束:EF migration for changing data type of columns

我使用那里的解决方案来DROP默认约束,我的迁移没有遇到任何问题。

回到索引,我添加了我的索引属性,所以我就这一点:

[Index]
[MaxLength(128)]
[Required]
public string LocationId { get; set; }

这次添加迁移 - >更新 - 数据库工作,瞧,我的索引已添加到数据库中。不幸的是,当我实际运行我的项目时,我现在正在获得一个新的SqlException ...

这一行:

IQueryable<TEntity> query = context.Set<TEntity>().AsNoTracking();

此例外:

A first chance exception of type 'System.Data.SqlClient.SqlException' occurred
in EntityFramework.dll

Additional information: The index 'IX_LocationId' is dependent on column
'LocationId'.

我不能为我的生活弄清楚这意味着什么...如果我从我的模型中删除[Index]属性,代码运行得很好,并且索引仍然存在于数据库中。 ..但这不是我可以在生产中运行的东西。

0 个答案:

没有答案