【问题标题】:ASP.NET MVC EF and MySQLASP.NET MVC EF 和 MySQL
【发布时间】:2015-01-28 03:07:37
【问题描述】:

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

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

这里有一个模型 Note.cs:

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

这里是 DataContext.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.

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

【问题讨论】:

  • 你可以删除 DropCreateDatabaseAlways() 并再次尝试
  • 并添加新的 DropCreateDatabaseIfModelChanges()
  • 稍后更新数据库
  • 是的,我之前试过这个,完全一样的错误

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


【解决方案1】:

注释掉不受支持的 DbInitializer 是第一步。我已经对您的代码进行了测试,并且可以正常工作。您可以从here 获得工作示例。我已经手动创建了 Note 表。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-22
    • 1970-01-01
    • 2020-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多