使用相同datacontext的多个查询会抛出SqlException

时间:2009-11-24 06:38:30

标签: c# linq-to-sql sql-server-2008-express

我正在搜索控件,我正在尝试将搜索作为用户类型来实现。我正在使用Linq to SQL来解除对数据库的查询。虽然它通常工作正常,但当用户非常快速地键入查询时,会抛出一些随机的SqlException。这些是我最近偶然发现的两个不同错误消息:

  

当前命令发生严重错误。结果(如果有的话)应该被丢弃。

     

读取器关闭时无效尝试调用Read。

修改:包含的代码

DataContextFactory类:

public DataContextFactory(IConnectionStringFactory connectionStringFactory)
{
    this.dataContext = new RegionDataContext(connectionStringFactory.ConnectionString);
}

public DataContext Context
{
    get { return this.dataContext; }
}

public void SaveAll()
{
    this.dataContext.SubmitChanges();
}

使用Unity注册IDataContextFactory

// Get connection string from Application.Current settings
ConnectionInfo connectionInfo = Application.Current.Properties["ConnectionInfo"] as ConnectionInfo;
// Register ConnectionStringFactory with Unity container as a Singleton
this.container.RegisterType<IConnectionStringFactory, ConnectionStringFactory>(new ContainerControlledLifetimeManager(),
    new InjectionConstructor(connectionInfo.ConnectionString));
// Register DataContextFactory with Unity container
this.container.RegisterType<IDataContextFactory, DataContextFactory>();

连接字符串:

Data Source=.\SQLEXPRESS2008;User Instance=true;Integrated Security=true;AttachDbFilename=C:\client.mdf;MultipleActiveResultSets=true;

使用来自存储库类的datacontext:

// IDataContextFactory dependency is injected by Unity
public CompanyRepository(IDataContextFactory dataContextFactory)
{
    this.dataContextFactory = dataContextFactory;
}

// return List<T> of companies
var results = this.dataContextFactory.Context.GetTable<CompanyEntity>()
        .Join(this.dataContextFactory.Context.GetTable<RegionEntity>(),
            c => c.regioncode,
            r => r.regioncode,
            (c, r) => new { c = c, r = r })
        .Where(t => t.c.summary_region != null)
        .Select(t => new { Id = t.c.compcode, Company = t.c.compname, Region = t.r.regionname }).ToList();

有什么工作?

1 个答案:

答案 0 :(得分:0)

这不是你的连接字符串中需要MARS的东西吗?

http://msdn.microsoft.com/en-us/library/h32h3abf(VS.80).aspx