微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

实体框架初始迁移因 SqlException 失败

如何解决实体框架初始迁移因 SqlException 失败

我想使用 EF 模型的代码优先方法创建 sql Server 数据库/表。 这是我的简单模型类

public class MyApplication
{
    [Key]
    public string AppID { get; set; }
    public string AppName { get; set; }
}

这里显示了我的 DBContext 类

public class PolicyDBContext : DbContext
{
    public PolicyDBContext(DbContextOptions options) : base(options)
    {
    }

    protected override void OnConfiguring(DbContextOptionsBuilder OptionaBuilder)
    {
        if (OptionaBuilder.IsConfigured)
        {
            OptionaBuilder.UsesqlServer(builder => builder.EnableRetryOnFailure());
        }
    }
    DbSet<MyApplication> AppRoles { get; set; }
}

这是我在 Startup.cs 中的配置代码

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<PolicyDBContext>(item => item.UsesqlServer("Server=MyServer;Database=MyDB;user id=testuid;Password=testpwd;");
}

然后我就可以成功运行“add-migration initialmigration”命令

enter image description here

但是当我运行“update-database”命令时,它总是失败并出现以下错误

Error Number:64,State:0,Class:20
A transient exception occurred during execution. The operation will be retried after 15024ms.
Microsoft.Data.sqlClient.sqlException (0x80131904): A connection was successfully established with the server,but then an error occurred during the pre-login handshake. (provider: TCP Provider,error: 0 - The specified network name is no longer available.)

然而,在执行“update-database”后,我注意到新数据库总是在我的 sql Server 上创建,但其中没有表。我认为这表明至少我的连接字符串是好的。

从上面的代码可以看出,我做了 EnableRetryOnFailure,正如人们在回答与我的类似问题时所建议的那样。但它并没有解决我的问题,只是它会重试几次(6)然后最终放弃。

在这里遗漏了什么?

解决方法

不确定为什么会这样,但我现在知道如何修复它。看来我需要运行两次 update-database 命令。第一次会失败,但正如我在帖子中提到的,将创建新的空数据库。现在,将空数据库留在那里 - 不要删除它! - 并再次运行 update-database 命令。这一次它会成功并创建表。

,

代码优先选项中有两种方法。您应该使用受保护的覆盖 void OnModelCreating(ModelBuilder modelBuilder) { } 您应该在此方法中定义配置。

有关详细信息,请访问此 link

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。