实体SetInitializer获得一个SQL超时

本文关键字:一个 SQL 超时 SetInitializer 实体 | 更新日期: 2023-09-27 18:07:33

使用Entity的视觉设计器,我已经创建了最基本的实体。我想将一些示例数据种子到我创建的数据库中,该数据库保存了Azure上这个基本实体的模式。我想使用这个数据库在asp.net web表单,但当我去种子init数据我得到一个SQL超时错误。

我知道,当使用实体数据库。SetInitializer种子操作只在使用上下文时调用,所以我强制初始化。它似乎尝试,但我仍然得到超时。我创建了一个基本的控制台应用程序,并编写了一个测试程序来加载一些值到表中,它工作得很好,所以我知道它不是连接到DB,它与播种有关。

下面是实际的错误:

A first chance exception of type 'System.Data.SqlClient.SqlException' occurred in EntityFramework.SqlServer.dll
An exception of type 'System.Data.SqlClient.SqlException' occurred in EntityFramework.SqlServer.dll but was not handled in user code
Additional information: Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.

上下文文件

namespace SlowTest.DB
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;
    public partial class ModelContainer : DbContext
    {
        public ModelContainer()
            : base("name=ModelContainer")
        {
        }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }
        public virtual DbSet<Books> Books { get; set; }
    }
}

实体类

namespace SlowTest.DB
{
    using System;
    using System.Collections.Generic;
    public partial class Books
    {
        public int BookId { get; set; }
        public string Author { get; set; }
    }
}

初始化

namespace SlowTest.DB
{
    public class Init : DropCreateDatabaseAlways<ModelContainer>
    {
        protected override void Seed(ModelContainer context)
        {
            GetBooks().ForEach(c => context.Books.Add(c));
        }
        private static List<Books> GetBooks()
        {
            var B = new List<Books>
            {
                new Books{
                    BookId = 0,
                    Author = "Neville",
                },
                new Books{
                    BookId = 3,
                    Author = "Steve",
                },
            };
            return B;
        }
    }
}

Global.asax.cs

namespace SlowTest
{
    public class Global : HttpApplication
    {
        void Application_Start(object sender, EventArgs e)
        {
            // Code that runs on application startup
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            Database.SetInitializer<ModelContainer>(new Init());
            ModelContainer db = new ModelContainer();
            db.Database.Initialize(true);
        }
    }
}

编辑

这是我的web.config。其中大部分是由visual studio或实体自动生成的

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)'v11.0;AttachDbFilename=|DataDirectory|'aspnet-SlowTest-20150812115338.mdf;Initial Catalog=aspnet-SlowTest-20150812115338;Integrated Security=True" providerName="System.Data.SqlClient" />
    <add name="ModelContainer" connectionString="metadata=res://*/DB.Model.csdl|res://*/DB.Model.ssdl|res://*/DB.Model.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=uvic.database.windows.net;initial catalog=TrojanDB;persist security info=True;user id=nhoughto;password=Password;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>
  <system.web>
    <authentication mode="None" />
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
    <pages>
      <namespaces>
        <add namespace="System.Web.Optimization" />
        <add namespace="Microsoft.AspNet.Identity" />
      </namespaces>
      <controls>
        <add assembly="Microsoft.AspNet.Web.Optimization.WebForms" namespace="Microsoft.AspNet.Web.Optimization.WebForms" tagPrefix="webopt" />
      </controls>
    </pages>
    <membership>
      <providers>
        <!--
          ASP.NET Membership is disabled in this template. Please visit the following link http://go.microsoft.com/fwlink/?LinkId=301889 to learn about the ASP.NET Membership support in this template
        -->
        <clear />
      </providers>
    </membership>
    <profile>
      <providers>
        <!--
          ASP.NET Membership Profile is disabled in this template. Please visit the following link http://go.microsoft.com/fwlink/?LinkId=301889 to learn about the ASP.NET Membership support in this template
        -->
        <clear />
      </providers>
    </profile>
    <roleManager>
      <!--
            ASP.NET Membership Role is disabled in this template. Please visit the following link http://go.microsoft.com/fwlink/?LinkId=301889 to learn about the ASP.NET Membership support in this template
        -->
      <providers>
        <clear />
      </providers>
    </roleManager>
    <!--
            If you are deploying to a cloud environment that has multiple web server instances,
            you should change session state mode from "InProc" to "Custom". In addition,
            change the connection string named "DefaultConnection" to connect to an instance
            of SQL Server (including SQL Azure and SQL  Compact) instead of to SQL Server Express.
      -->
    <sessionState mode="InProc" customProvider="DefaultSessionProvider">
      <providers>
        <add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" />
      </providers>
    </sessionState>
  </system.web>
  <system.webServer>
    <modules>
      <remove name="FormsAuthentication" />
    </modules>
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" culture="neutral" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="EntityFramework" publicKeyToken="b77a5c561934e089" />
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin" culture="neutral" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security.OAuth" culture="neutral" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security.Cookies" culture="neutral" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security" culture="neutral" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

实体SetInitializer获得一个SQL超时

我知道这是一个老问题,但万一有人从谷歌绊倒…您需要增加CommandTimeout以给Azure足够的时间来创建数据库。

这里有一个非常详细的StackOverlow答案解释了为什么:设置连接到Azure的实体框架超时

它的要点是,您需要在DbContext构造函数中添加一行:
public MyContext() : base("name=MyContext")
{
    // three minute command timeout
    this.Database.CommandTimeout = 180;
}