Entity Framework Code First - Create Database with MySql? [closed]

淺唱寂寞╮ 提交于 2019-12-08 04:50:47

问题


I just wanted to try Entity Framework to use it instead of NHibernate. I'm using a MySql database. So I did few tests with the code first system. Everything is ok with MsSql the database and the schema is auto generated. But then I tried it with MySql and the schema generation doesn't work.

public class Context : DbContext
{
    public Context()
    {

    }

    public Context(string str)
        : base (str)
    {

    }

    public DbSet<User> Users
    {
        get;
        set;
    }
}

public class User
{
    public int Id
    {
        get;
        set;
    }

    public string Name
    {
        get;
        set;
    }
}

class Program
{
    static void Main(string[] args)
    {
      var sqlBuilder =
            new SqlConnectionStringBuilder
            {
                DataSource = "localhost",
                InitialCatalog = "test",
                Password = "",
                UserID = "root"
            };

        var entityBuilder =
            new EntityConnectionStringBuilder
            {
                Provider = "MySql.Data.MySqlClient",
                ProviderConnectionString = sqlBuilder.ConnectionString,
                Metadata = @"res://*"
            };

        var str = entityBuilder.ConnectionString;

        using (var ctx = new Context(str)) 
        {

            ctx.Users.Add(new User() // exception here
            {
                Name = "test"
            });

            ctx.SaveChanges();
        }

        using (var ctx = new Context(str))
        {
            foreach (var user in ctx.Users)
            {
                Console.WriteLine("id:{0} name:{1}", user.Id, user.Name);
            }
        }
    }
}

And I got this exception : "The entity type User is not part of the model for the current context."

So here is my question, can I generate the database automatically if I use MySql ?


回答1:


I dunno why it works but it does now. I removed the connection properties from the code and I've created an app.config file and correct a bug at the database creation with this blog http://brice-lambson.blogspot.fr/2012/05/using-entity-framework-code-first-with.html and now it works



来源:https://stackoverflow.com/questions/11766466/entity-framework-code-first-create-database-with-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!