实体框架种子-> SqlException:重置连接将导致状态不同于初始登录.登录失败. [英] Entity Framework seed -> SqlException: Resetting the connection results in a different state than the initial login. The login fails.
问题描述
运行Entity Framework的seed方法时,出现以下异常.我只有一次异常,如果在数据库已经被更改时第二次运行seed方法,则代码可以正常工作.我该怎么做,以使我在第一次创建数据库时不必两次运行代码?我不会使用种子,也不会使用自定义迁移来更改数据库.
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:重置连接将导致状态不同于初始登录.登录失败.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!