我有以下 Code First 实体:
public class Department
{
public int DepartmentID { get; set; }
public string DepartmentName { get; set; }
}
我设置的配置如下表:
dbo.Departments
DepartmentID INT PRIMARY KEY
DepartmentName VARCHAR(75)
我手动向 DepartmentName 添加了索引并运行以下查询:
var depts = new string[] { "Engineering", "Manufacturing" };
var departments = from d in db.Departments
where depts.Contains(d.DepartmentName)
select d;
当我运行跟踪时,它产生了以下 SQL:
SELECT
[Extent1].[DepartmentID] AS [DepartmentID],
[Extent1].[DepartmentName] AS [DepartmentName]
FROM [dbo].[Departments] AS [Extent1]
WHERE [Extent1].[DepartmentName] IN (N'Engineering',N'Manufacturing')
由于我的列是 varchar 并且查询将文本转换为 NVARCHAR,因此优化器选择在我的 DepartmentName 索引上执行聚集索引扫描而不是索引查找。
除了将我的数据库更改为使用 nvarchar 之外,还有什么方法可以解决这个问题?这是一个错误还是这是正常的?