ASP.NET MVC EF and MySQL

本文关键字:and MySQL EF MVC NET ASP | 更新日期: 2023-09-27 18:32:31

我遵循本教程:http://www.asp.net/identity/overview/getting-started/aspnet-identity-using-mysql-storage-with-an-entityframework-mysql-provider一切都按预期工作。

但是

现在我想将我的模型添加到应用程序中,但是在连接以创建数据库时遇到问题

这里一个模型注.cs:

public class Note
    {
        public int Id { get; set; }
        public string Text { get; set; }
        public int Done { get; set; }
    }

这里是数据上下文.cs

public class DataContext : DbContext
    {
        public DataContext()
            : base("DefaultConnection")
        {
        }
        public DbSet<Note> Note { get; set; }
        static DataContext()
        {
            Database.SetInitializer<DataContext>(
            new DropCreateDatabaseAlways<DataContext>());
        }
    }

和 HomeController.cs:

private DataContext db = new DataContext();
        public ActionResult Index()
        {
            var note = new Note { Id = 1, Text = "this is the text", Done = 0 };
            db.Note.Add(note);
            db.SaveChanges();
            ViewBag.Notes = db.Note.ToList();
            return View();
        }

当我登录时,一切都很完美,它为用户创建数据库。但是当我转到此控制器时,我在db.Note.Add(note);上收到此错误:

An exception of type 'System.NotSupportedException' occurred in EntityFramework.dll but was not handled in user code
Additional information: Model compatibility cannot be checked because the database does not contain model metadata. Model compatibility can only be checked for databases created using Code First or Code First Migrations.

如何让我的代码根据模型创建数据库?

ASP.NET MVC EF and MySQL

注释

掉不受支持的 DbInitializer 是第一步。我已经用您的代码进行了测试,它可以工作。您可以从此处获取工作示例。我已经手动创建了笔记表。