首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用via LINQ查询的SQL Server中的超时异常

使用via LINQ查询的SQL Server中的超时异常
EN

Stack Overflow用户
提问于 2018-08-08 16:56:48
回答 1查看 142关注 0票数 4
代码语言:javascript
复制
select Max(ma.Coloumn2), mcp.column2 from Entity1 mr 
    JOIN Entity2 mcp on mr.column1 = mcp.column1 
    JOIN Entity3 ma on mcp.column1 = ma.column1 
    where mr.column3 = XXX GROUP by mcp.column2 

我有一个上面提到的问题。在我的Entity1中大约有200,000行,在实体3中有20k行,在实体2中只有40行。

这个查询在SQL中大约在4分钟内执行,在LINQ中它给出超时异常。但是当我重建entity2的索引时,它会在微秒内给出结果,2-3天后问题再次出现,然后我重建索引,然后问题就消失了。

我无法确定此问题的根本原因。有人能帮我吗?

EN

回答 1

Stack Overflow用户

发布于 2018-08-08 22:57:25

别忘了通知Entity Framework你的索引。在你的DbContext.OnModelCreating

代码语言:javascript
复制
modelBuilder.Entity<Person>()
   .Property(person => person.Name)
   .IsRequired()
   .HasColumnAnnotation(IndexAnnotation.AnnotationName, 
        new IndexAnnotation(
            new IndexAttribute("IndexPersonNames", 0)));

这是相当不可读的。因为我必须对许多属性执行此操作,所以我决定创建一个扩展函数:

代码语言:javascript
复制
static PrimitivePropertyConfiguration HasIndex(
    this PrimitivePropertyConfiguration property,
    string indexName,
    int columnOrder,
    bool uniqueIndexValues = false)
{
    var indexAttribute = new IndexAttribute(indexName, columnOrder)
    {
        IsUnique = uniqueIndexValues,
    };
    var indexAnnotation = new IndexAnnotation(indexAttribute);

    return property.hasColumnAnnotation(IndexAnnotation.AnnotationName, indexAnnotation);
}

上面的modelBuilder语句将是:

代码语言:javascript
复制
 modelBuilder.Entity<Person>()
   .Property(person => person.Name)
   .IsRequired()
   .HasIndex("indexPersonNames", 0)));

或者,如果您想在两列上建立索引:

代码语言:javascript
复制
.IsRequired()
.HasIndex("indexSurName", 0)         // first index by SurName
.HasIndex("indexFirstName", 1)       // then by FirstName
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51742548

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档