c# - EntityCommandExecutionException

时间:2014-03-03 17:29:34

标签: c# asp.net-mvc

我正在创建一个连接到LocalDB的小型新闻网站(用于练习)。

我根据自己的需要调整了本教程:http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application

NewsItem类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.WebPages.Html;
using System.ComponentModel.DataAnnotations;

namespace NewsApp.Models
{
    public class NewsItem
    {
        public int ID { get; set; }
        [Required(ErrorMessage="Title is required.")]
        public string Title { get; set; }
        [Required(ErrorMessage="Content is required.")]
        public string Content { get; set; }
        public string Category { get; set; }
        public DateTime Date { get; set; }

        public NewsItem()
        {
            Date = DateTime.Now;
        }
    }
}

NewsContext:

using NewsApp.Models;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;

namespace NewsApp.DAL
{
    public class NewsContext : DbContext
    {

        public NewsContext() : base("NewsContext")
        {
        }

        public DbSet<NewsItem> NewsItem { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        }
    }
}

在HomeController.cs中:

private NewsContext db = new NewsContext();

public ActionResult Index()
{
    // This throws EntityCommandExecutionException
    return View(db.NewsItem.OrderByDescending(u => u.ID).Take(10).ToList());
}

最后,Web.config:

<?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=301880
  -->
<configuration>
  <configSections>

    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --></configSections>
  <connectionStrings>
    <add name="NewsContext" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=NewsApp1;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
  </connectionStrings>
  <appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
  <system.web>
    <authentication mode="None" />
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
  </system.web>
  <system.webServer>
    <modules>
      <remove name="FormsAuthenticationModule" />
    </modules>
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <entityFramework>
    <contexts>
      <context type="NewsApp.DAL.NewsContext, NewsApp">
        <databaseInitializer type="NewsApp.DAL.NewsInitializer, NewsApp" />
      </context>
    </contexts>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="v11.0" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

每次运行它我都会在Index中获得EntityCommandExecutionException。当我在Visual Studio中打开Server Explorer并在NewsContext下查看表时,NewsItem不在其中(仅限_MigrationHistory)。

此代码几天前正在运行,但我通过使用.sql文件手动删除了表:

DROP TABLE NewsItem

从那以后它还没有创建表。我试图对代码进行一段时间的故障排除,但后来决定开始一个新项目(认为它会起作用),但它仍然没有创建表。

Visual Studio是否将.sql文件保存在某处并继续运行?

你能在我的代码中看到任何明显的错误吗?

感谢。

编辑:

我也有这个NewsInitializer.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using NewsApp.Models;

namespace NewsApp.DAL
{
    public class NewsInitializer : System.Data.Entity. DropCreateDatabaseIfModelChanges<NewsContext>
    {
        protected override void Seed(NewsContext context)
        {
            var NewsItems = new List<NewsItem>
            {
                new NewsItem{   Title="Some crap test news",
                                Content="Yeah.",
                                Category="News"},
            };

            NewsItems.ForEach(s => context.NewsItem.Add(s));
            context.SaveChanges();
        }
    }
}

0 个答案:

没有答案