ここに良い方法があります。
public static class ConnectionManager
{
public static string GetSqlConnectionString()
{
var serverName = @"" + ConfigurationManager.AppSettings["ServerName"];
var databaseName = ConfigurationManager.AppSettings["DatabaseName"];
var username = ConfigurationManager.AppSettings["Username"];
var password = ConfigurationManager.AppSettings["Password"];
SqlConnectionStringBuilder providerCs = new SqlConnectionStringBuilder();
providerCs.DataSource = serverName;
providerCs.InitialCatalog = databaseName;
//providerCs.IntegratedSecurity = true;
//providerCs.UserInstance = true;
providerCs.UserID = username;
providerCs.Password = password;
var csBuilder = new EntityConnectionStringBuilder();
csBuilder.Provider = "System.Data.SqlClient";
csBuilder.ProviderConnectionString = providerCs.ToString();
csBuilder.Metadata = string.Format("res://{0}/yourDataBase.csdl|res://{0}/yourDataBase.ssdl|res://{0}/yourDataBase.msl",
typeof(yourDataBaseEntities).Assembly.FullName);
return csBuilder.ToString();
}
}
使用法:
あなたのapp.config
代わりにこのコード
<appSettings>
<add key="ServerName" value="UNKNOWN01-PC\sampleServer"/>
<add key="DatabaseName" value="samplDatabase"/>
<add key="Username" value="sampleUser"/>
<add key="Password" value="sampPass"/>
</appSettings>
それで、
string connectionString = GetSqlConnectionString();
using (MyEntities entities = new MyEntities(connectionString))
{
MyDataEntity myDataEntity = new MyDataEntity();
// Save to the database
entities.MyDataEntity.Add(myDataEntity);
entities.SaveChanges();
}