【问题标题】:Controller not creating DataContext, FileNotFoundException控制器未创建 DataContext,FileNotFoundException
【发布时间】:2016-03-08 20:34:31
【问题描述】:

所以我首先通过创建博客来学习 MVC 和 EF7 代码。每次单击发送博客文章按钮时,我都会收到 500 内部服务器错误,这应该创建一个新的本地数据库并插入文章。将表单数据发送到控制器的视图工作正常我已经用断点检查过它,但它在这一行中断

var db = new BlogDataContext();

这是我的 BlogDataContext

namespace test.Models
{
    public class BlogDataContext : DbContext
    {
        public DbSet<Post> Post { get; set; }

        public BlogDataContext()
        {
            Database.EnsureCreated();
        } /// This row is marked red on my error page after i press the send blog post button

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            base.OnConfiguring(optionsBuilder);

            var connectionString = @"Server=(LocalDB)\MSSQLLocalDB;Database=test;";
            optionsBuilder.UseSqlServer(connectionString);
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.ForSqlServer().UseIdentity();

        }

    }
}

来自我的控制器的相关方法

[HttpPost]
        public IActionResult Create(Post post)
        {
            if (!ModelState.IsValid)
            {
                return View(post);
            }

            post.PostedDate = DateTime.Now; // Breakpoint here shows the datetime just fine after pressing the Send button.
            post.Author = User.Identity.Name; // This is null for now

            var db = new BlogDataContext();                 db.Post.Add(post);
            db.SaveChanges();
            return View();

错误页面图片

我还确保 MSSQLLocalDB 已启动

【问题讨论】:

    标签: c# asp.net asp.net-mvc entity-framework entity-framework-core


    【解决方案1】:

    所以我的依赖是错误的,我的 DNX 版本是 beta5,而我的 entityframework.sqlserver 是 beta4,所以我将它升级到 beta5,但在 OnConfiguring 和 DbContextOptionsBuilder 上出现错误。它找不到那个覆盖。

    所以我把所有东西都转回了 beta4,它可以工作,尽管网站在 iis express 中加载速度较慢。

    【讨论】:

      猜你喜欢
      • 2014-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多