EF6/Code 首先是索引: access/use 索引有什么特别之处吗?

EF6/Code First and indexes: Is there anything special to do to access/use indexes?

我正在进行我的第一个 Code First 项目。我刚刚学会了如何在两列上添加索引。

    [Required]
    [Index("IX_NameAndCity", 1, IsUnique = false)]
    [MaxLength(900)]
    public string Name { get; set; }

    [Index("IX_NameAndCity", 2, IsUnique = false)]
    [MaxLength(900)]
    public string City { get; set; }

这样看起来对吗? ^^^

LINQ 中使用这些索引有什么特别之处吗?还是透明的?我有一半希望在我的 LINQ 中看到 '.IX_NameAndCity'.

的选择

这是我现在正在做的事情:

 var property = _propertyRepository
            .GetProperties()
            .FirstOrDefault(x => x.Name == name && x.City == city);

应该是这样的:

 var property = _propertyRepository
            .GetProperties()
            .FirstOrDefault(x => x.IX_NameAndCity.name == name && IX_NameAndCity.City == city);

或者它会自动知道有索引吗? 谢谢大家!

索引是在数据库服务器上创建的。就像您不想在编写 SQL 查询时显式引用索引一样,您也不想在编写 LINQ 查询时显式引用索引。实际上你的实体不会有 IX_NameAndCity 属性。所以只需使用您的第一个查询:

var property = _propertyRepository
    .GetProperties()
    .FirstOrDefault(x => x.Name == name && x.City == city);

Entity Framework会构造对应的SQL查询并传递给数据库服务器,数据库服务器就会知道应该(或可能不应该)使用索引来加速查询执行。它是透明的;不用担心。