在C#中的实体数据模型中动态设置连接字符串

时间:2013-01-16 14:07:39

标签: c# entity-framework

我正在开发一个依赖于ADO.NET实体数据模型的项目。我有4个相同的数据库模式,一个用于我公司的每个部门(Marketing,Finanace,Administrative和HR)。我目前知道每个用户所在的部门。我想使用该部门来确定用户可以连接到哪个数据库。

在C#代码中,如何在运行时设置连接字符串?目前,我有

string connectionString = GetUsersConnectionString();
using (MyEntities entities = new MyEntities())
{
  MyDataEntity myDataEntity = new MyDataEntity();

  // Save to the database
  entities.MyDataEntity.Add(myDataEntity);
  entities.SaveChanges();
}

我在这里缺少什么?如何将MyEntities的连接字符串设置为connectionString

3 个答案:

答案 0 :(得分:1)

这是一种很好的方法。

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();
}

答案 1 :(得分:0)

使用:

string connectionString = GetUsersConnectionString();
using (MyEntities entities = new MyEntities(new EntityConnection(connectionString )))
{
  MyDataEntity myDataEntity = new MyDataEntity();

  // Save to the database
  entities.MyDataEntity.Add(myDataEntity);
  entities.SaveChanges();
}

答案 2 :(得分:0)

在Model.Designer.cs文件中,您必须初始化一个新的Entities对象,该对象获取所需数量的参数。例如:

namespace:MyModel
{
#region Contexts 
public partial class MyEntities : ObjectContext
{
    #region Constructors

public MyEntities(EntityConnection connection) //add the required arguments
        : base(connection, "Entities")
    {
        this.ContextOptions.LazyLoadingEnabled = true;
        OnContextCreated();
    }
....

然后使用您的新实体来操纵连接字符串检索的任何数据,例如

 MyModel.MyEntities db = new MyModel.Entities(connectionString);
 var query = from rows in db.Table_Name orderby rows.ID select rows;