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:重置连接会导致与初始登录不同的状态.登录失败.
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 输入按键事件处理程序 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
