【发布时间】:2012-07-31 17:09:45
【问题描述】:
我在实体框架中有 2 个非常简单的查询,它们按作为外键的列分组。换句话说,表格字段是:
pk : Primary key
name : name of object
f1: foreign key1
f2: foreign key2
...
我收到超时异常,尤其是这个:
Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
查询是:
var q = from x in db.Table select x;
var query_1 = q.GroupBy (record => record.f1);
var query2 = q.GroupBy(record => new {record.f1, record.f2});
我在 DB 中有大约 30,000 条记录,我不明白为什么简单的 group by 会超时。你对我应该怎么做有什么建议吗?由于我使用的是 Entity Framework 4.1,我想从实现中抽象出数据库,所以我想要一个不会改变数据库引擎本身的任何东西的解决方案。 索引 f1 或 f2(或两者)字段可以让我更快地查询吗?如果是这样,有人可以解释索引的概念以及在 Enfity Framework 中如何做吗? 我不认为增加超时应该是我应该解决的唯一解决方案,我担心随着更多数据的到来,问题仍然存在。
编辑: 我已经尝试过here 提到的关于 EF 迁移的内容。
我有这门课:
namespace DataAccessLayer.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class IX_Table1_fId : DbMigration
{
public override void Up()
{
Console.WriteLine("Creating Index");
CreateIndex("Table1", "fId");
Console.WriteLine("Index Created");
}
public override void Down()
{
DropIndex("Table1", "IX_Table1_fId");
}
}
}
但是,这段代码什么时候被调用?我在控制台中看不到打印语句。
【问题讨论】:
-
Up和Down方法在应用程序启动时自动调用(如果您有默认的 DB 初始化程序),或者当您在包管理器控制台中显式键入update-database时。在后一种情况下,控制台输出消失在黑洞中。
标签: c# .net linq entity-framework query-optimization