【发布时间】:2021-07-11 16:05:55
【问题描述】:
使用Entity Framework 6.0.0.0 时出现以下错误。
在创建模型时不能使用上下文。 如果在
内部使用上下文,则可能会引发此异常 OnModelCreating 方法或 如果相同的上下文实例 由多个线程同时访问。 请注意,DbContext 的实例成员和 不保证相关类是线程安全的。 它在async方法内触发 ,更新:
public async Task<IList<Model>> GetEntities(filter f)
{
using (var db = new MyDbContext())
{
var query = db.MyDbSet.AsQueryable();
if (f != null && f.field.Any())
//Exception throwed here
query = query.Where(a => f.field.Contains(a.field));
return await query.ToListAsync();
}
}
但是当我尝试通过Where 子句查找我的实体时,不会执行任何await 调用或其他多线程操作。
是否有与该问题相关的建议?我找到了很多答案,但没有发现它们对我有帮助。
【问题讨论】:
-
贴出更完整的代码。正如您可能想象的那样,这段代码看起来完全是无辜的,无法从中诊断出来。
-
@usr 我添加了代码
-
好的。现在请完整的异常 ToString 因为代码对我来说很好。
-
看来原因是下面的错误
Additional information: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)但是Management studio已经连接没有问题。以下连接字符串对于 win authData Source=host;Initial Catalog=database;Integrated Security=True;是否正确? -
听起来这两个错误不相关。再次,发布完整的 ToString 输出。里面有很多信息。
标签: c# entity-framework async-await