Mysql自定义连接字符串

时间:2014-04-15 12:54:59

标签: c# mysql entity-framework-5

我有安装了mysql连接器的实体框架5(对于vs 1.1.3和mysql连接器6.8.3的mysql)并且在我的app.config中有一个连接字符串:

<add name="applicantDBEntities" connectionString="metadata=res://*/Models.applicantsDBModel.csdl|res://*/Models.applicantsDBModel.ssdl|res://*/Models.applicantsDBModel.msl;provider=MySql.Data.MySqlClient;provider connection string=&quot;server=localhost;user id=root;database=applicantsdb&quot;" providerName="System.Data.EntityClient" />

如果我在app.config中使用连接字符串,一切正常,但我希望用户能够选择他的服务器,用户名,密码和数据库。我是如何尝试实现它的:

public partial class applicantDBEntities : DbContext
    {
        public applicantDBEntities()
            : base("name=applicantDBEntities")
        {
        }

        public applicantDBEntities(string connectionString) : base (connectionString)
        {

        }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }

        public DbSet<applicant> applicants { get; set; }
        public DbSet<file> files { get; set; }
    }

初始化本身:

CONNECTION_PATTERN = "server={0};database={1};User Id={2};password={3}";
this.dbContext = new applicantDBEntities(String.Format(CONNECTION_PATTERN, 
                Settings.GetInstance().Server, Settings.GetInstance().Database, 
                Settings.GetInstance().User, Settings.GetInstance().Password));

但无论我作为参数传递什么(甚至是错误的),我总是以OnModelCreating方法结束。

这样做的正确方法是什么?

修改: 正如@Andrew提到的,我的连接字符串是错误的。这就是我现在的做法:

string connectionString = new System.Data.EntityClient.EntityConnectionStringBuilder
            {
                Metadata = "res://*",
                Provider = "MySql.Data.MySqlClient",
                ProviderConnectionString = new System.Data.SqlClient.SqlConnectionStringBuilder
                {
                    InitialCatalog = Settings.GetInstance().Database,
                    DataSource = Settings.GetInstance().Server,
                    IntegratedSecurity = false,
                    UserID = Settings.GetInstance().User,
                    Password = Settings.GetInstance().Password
                }.ConnectionString
            }.ConnectionString;
this.dbContext = new applicantDBEntities(connectionString);

1 个答案:

答案 0 :(得分:1)

您的连接字符串格式无效。 它应该类似于:

"metadata=res://*/Northwind.csdl|  
          res://*/Northwind.ssdl|  
          res://*/Northwind.msl;  
 provider=System.Data.SqlClient;  
 provider connection string=  
          &quot;Data Source=.\sqlexpress;  
          Initial Catalog=Northwind;  
          Integrated Security=True;  
          MultipleActiveResultSets=True&quot;"

并且可能基于EntityConnectionStringBuilder

http://msdn.microsoft.com/en-us/data/jj592674.aspx这里有关于如何连接到数据库的不同场景和框架版本的描述