我在实体框架中有 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 中如何做吗?我不认为增加超时应该是我应该解决的唯一解决方案,我担心随着更多数据的到来,这个问题仍然存在。
编辑:我已经尝试过这里提到的关于 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");
}
}
}
但是,何时调用此代码?我没有看到控制台中的打印语句。