【问题标题】:EF6/Code First and indexes: Is there anything special to do to access/use indexes?EF6/Code First 和索引:访问/使用索引有什么特别的事情要做吗?
【发布时间】:2015-07-24 17:46:48
【问题描述】:

我在我的第一个 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);

或者它是否自动知道有一个索引? 谢谢大家!

【问题讨论】:

    标签: linq indexing ef-code-first


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-24
      • 2020-01-26
      • 2016-07-04
      • 1970-01-01
      • 1970-01-01
      • 2010-10-29
      • 2010-09-10
      相关资源
      最近更新 更多