1.使用entityConnectionStringBuilder 创建连接字符串
public static string GetConnStr(string host, string catalog, string user, string pass, bool winAuth=false) { SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder { DataSource = host, InitialCatalog = catalog, PersistSecurityInfo = true, IntegratedSecurity = winAuth, MultipleActiveResultSets = true, UserID = user, Password = pass, }; // assumes a connectionString name in .config of MyDbEntities var entityConnectionStringBuilder = new EntityConnectionStringBuilder { Provider = "System.Data.SqlClient", ProviderConnectionString = sqlBuilder.ConnectionString, Metadata = "res://*/FaceDB.csdl|res://*/FaceDB.ssdl|res://*/FaceDB.msl", //此处需修改为正确的字符(观察并复制web.config中的即可) }; return entityConnectionStringBuilder.ConnectionString; }
将此方法返回的字符串传递进一个参数的构造函数实例化datacontext:参考http://www.voidcn.com/article/p-fllvvzft-btb.html
FaceEntities dc = new FaceEntities(GetConnStr(xxxx,xxx,xx,xx));
2.写死字符串模板并动态替换
public static string connTemplate = "metadata=res://*/FaceDB.csdl|res://*/FaceDB.ssdl|res://*/FaceDB.msl;provider=System.Data.SqlClient;provider connection string="Data Source = {{DBIp}}; Initial Catalog ={{DBName}}; Integrated Security = False; Persist Security Info=True;User ID = {{DBUser}}; Password={{DBPwd}};MultipleActiveResultSets=True"";
也需注意metadata里的值修改.(观察并复制web.config中的即可)
var connString = connTemplate.Replace("{{DBIp}}","192.168.x.x").Replace("{{DBName}}", "FaceDB").Replace("{{DBUser}}","sa").Replace("{{DBPwd}}","sa");
FaceEntities dc = new FaceEntities(connString);