问题描述
运行实体框架的种子方法时出现以下异常.我只得到一次异常,如果我在数据库已经更改时第二次运行种子方法,代码就可以工作.我该怎么做才能在第一次创建数据库时不必运行两次代码?我不想使用种子,也不想使用自定义迁移来更改数据库.
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:重置连接会导致与初始登录不同的状态.登录失败.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!