设置实体框架连接字符串在运行时在C# [英] Set Entity Framework Connection String at Runtime in C#

查看:109
本文介绍了设置实体框架连接字符串在运行时在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在运行时设置我的实体框架连接字符串。现在,我有以下几点:

I need to set my Entity Framework connection string at runtime. Right now, I have the following:

string connectionString = "metadata=res://*/DataModels.CustomerDataModel.csdl|res://*/DataModels.CustomerDataModel.ssdl|res://*/DataModels.CustomerDataModel.msl;provider=System.Data.SqlClient;provider connection string="data source=tcp:{serverName},{portNumber};initial catalog={databaseName};user id={username};multipleactiveresultsets=True;application name=EntityFramework"";
using (CustomerEntities entities = new CustomerEntities(connectionString))
{
  CustomerEntity entity = new CustomerEntity();
  // do more
  entities.CustomerEntities.Add(entity);
  entities.SaveChanges();
}

当我执行上面的代码(与替换{参数}值)我收到以下错误:

When I execute the code above (with the {parameter} values replaced), I get the following error:

不支持关键字:数据源

我在做什么错了?

推荐答案

更改此

string connectionString = "metadata=res://*/DataModels.CustomerDataModel.csdl|res://*/DataModels.CustomerDataModel.ssdl|res://*/DataModels.CustomerDataModel.msl;provider=System.Data.SqlClient;provider connection string="data source=tcp:{serverName},{portNumber};initial catalog={databaseName};user id={username};multipleactiveresultsets=True;application name=EntityFramework"";

要这样(注意:我如何逃脱字符为)

To this (note how i escaped the " character as "" )

string connectionString = @"metadata=res://*/DataModels.CustomerDataModel.csdl|res://*/DataModels.CustomerDataModel.ssdl|res://*/DataModels.CustomerDataModel.msl;provider=System.Data.SqlClient;provider connection string= ""data source=tcp:{serverName},{portNumber};initial catalog={databaseName};user id={username};multipleactiveresultsets=True;application name=EntityFramework""";

这篇关于设置实体框架连接字符串在运行时在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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