Entity Framework seed -gt; SqlException: Resetting the connection results in a different state than the initial login. The login fails.(实体框架种子 -SqlException:重置连接会导致与初始登录不同的状态.登录失败.)
问题描述
运行实体框架的种子方法时出现以下异常.我只得到一次异常,如果我在数据库已经更改时第二次运行种子方法,代码就可以工作.我该怎么做才能在第一次创建数据库时不必运行两次代码?我不想使用种子,也不想使用自定义迁移来更改数据库.
I get the following exception when running the seed method for Entity Framework. I only get the exception once, if I run the seed method a second time when the database has already been altered the code works. What can I do so that I don't have to run the code twice when creating the database the first time? I wan't to use seed and not alter the database using a custom migration.
SqlException:重置连接会导致不同的状态比初始登录.登录失败.用户 '' 登录失败.无法继续执行,因为会话处于终止状态状态.
SqlException: Resetting the connection results in a different state than the initial login. The login fails. Login failed for user ''. Cannot continue the execution because the session is in the kill state.
protected override void Seed(Repositories.EntityFramework.ApplicationDbContext context)
{
context.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction,
string.Format("ALTER DATABASE [{0}] COLLATE Latin1_General_100_CI_AS", context.Database.Connection.Database));
//Exception here
context.Roles.AddOrUpdate(
role => role.Name,
new ApplicationRole() { Name = RoleConstants.SystemAdministrator }
);
}
如果我不使用 TransactionalBehavior.DoNotEnsureTransaction 我会在 context.Database.ExecuteSqlCommand
If I don't use TransactionalBehavior.DoNotEnsureTransaction I get the exception on context.Database.ExecuteSqlCommand
多语句中不允许使用 ALTER DATABASE 语句交易.
ALTER DATABASE statement not allowed within multi-statement transaction.
推荐答案
您可以通过使用普通的 ADO.Net 连接来解决此问题,因此不会重置上下文的连接:
You can fix this issue by using a plain ADO.Net connection, so the context's connection won't be reset:
using (var conn = new SqlConnection(context.Database.Connection.ConnectionString))
{
using (var cmd = conn.CreateCommand())
{
cmd.CommandText =
string.Format("ALTER DATABASE [{0}] COLLATE Latin1_General_100_CI_AS",
context.Database.Connection.Database));
conn.Open();
cmd.ExecuteNonQuery();
}
}
这篇关于实体框架种子 ->SqlException:重置连接会导致与初始登录不同的状态.登录失败.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:实体框架种子 ->SqlException:重置连接会导致与初始登录不同的状态.登录失败.
基础教程推荐
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 将数据集转换为列表 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 如果条件可以为空 2022-01-01
- 从 C# 控制相机设备 2022-01-01
