实体框架代码首先 - 使用MySql创建数据库? [英] Entity Framework Code First - Create Database with MySql?

查看:147
本文介绍了实体框架代码首先 - 使用MySql创建数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想尝试使用实体框架来代替NHibernate。我使用的是MySql数据库。
所以我用代码第一个系统做了很少的测试。 MsSql的一切都可以,数据库和模式是自动生成的。但是后来我用MySql尝试过,而且模式生成不起作用。

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."

所以这里是我的问题,我可以自动生成数据库吗我使用MySql?

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

推荐答案

我不知道为什么它的工作,但它现在。我从代码中删除了连接属性,我创建了一个app.config文件,并通过此博客更正了创建数据库的错误 http://brice-lambson.blogspot.fr/2012/05/using-entity-framework-code-first-with.html ,现在它的作品

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

这篇关于实体框架代码首先 - 使用MySql创建数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆