在运行时设置实体框架连接字符串 [英] Set Entity Framework connection string at runtime

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

问题描述

我已经从AdventureWorks数据库生成了实体模型;现在我想删除app.config中的连接字符串,并在运行时设置它。在Model1.Context.cs文件中,我已经将构造函数发送到

  public AdventureWorksEntities(string str)
:base (name = AdventureWorksEntities)
{
this.Database.Connection.ConnectionString = str;
}

和program.cs文件

  EntityConnectionStringBuilder ecsb = new EntityConnectionStringBuilder(); 
ecsb.Metadata = @res://*/Model1.csdl | res://*/Model1.ssdl | res://*/Model1.msl;
ecsb.Provider = @System.Data.SqlClient;
ecsb.ProviderConnectionString =
@data source = .\sqlexpress;初始目录= AdventureWorks;集成安全= True; MultipleActiveResultSets = True; App = EntityFramework;

using(var ent = new AdventureWorksEntities(ecsb.ConnectionString))
{
Console.WriteLine(ent.Database.Connection.ConnectionString);
var add = ent.Addresses;
foreach(var ad in add)
{
Console.WriteLine(ad.City);
}


}
Console.ReadKey();

现在,它表示没有找到元数据关键字。

解决方案

这是一个使用标准的.aspx登录信息来设置UserID和密码的例子连接字符串中的信息。没有连接字符串设置存储在web.config或app.config文件中。



修改Model.Designer.cs页面如下:

  public partial class Entities:ObjectContext 
{
#region构造函数


public static string getConStrSQL(string UID,string PWD)
{

string connectionString = new System.Data.EntityClient.EntityConnectionStringBuilder
{
Metadata =res:// * ,
Provider =System.Data.SqlClient,
ProviderConnectionString = new System.Data.SqlClient.SqlConnectionStringBuilder
{
InitialCatalog =your_database_name,
DataSource = your_server,
IntegratedSecurity = false,
UserID = UID,
Password = PWD,
} .ConnectionString
} .ConnectionString;

return connectionString;
}

///< summary>
///初始化一个新的Entities对象。
///< / summary>
public Entities(string UID,string PWD)
:base(getConStrSQL(UID,PWD),Entities)
{
this.ContextOptions.LazyLoadingEnabled = true;
OnContextCreated();
}
...

然后在你的代码页面:

  using System; 
使用System.Collections.Generic;
使用System.Linq;
使用System.Web;
使用System.Web.UI;
使用System.Web.UI.WebControls;
使用System.Web.Mvc;
使用System.Web.Security;


public partial class views_html_form:System.Web.UI.Page
{
public void Page_Load()
{
if(currentUser ()== null)
{
HttpContext.Current.Response.Redirect(〜/ login.aspx);
}
}
public static MembershipUser currentUser()
{
MembershipUser currentUser = Membership.GetUser();
return currentUser;
}

public static string UID()
{
string UID = currentUser()。UserName;
返回UID;
}
public static string PWD()
{
string PWD = currentUser()。GetPassword();
返回PWD;
}
public static void SelectRecord()
{
YourModel.Entities db = new YourModel.Entities(UID(),PWD());
var query = from db.Table_Name中的行orderby rows.ID select rows;
.....

就是这样。没有乱七八糟的.config文件。或者,您可以以相同的方式发送数据库名称,例如作为参数。


I have generated entity model from AdventureWorks database; now I want to delete the connection string in app.config and set it at runtime. In the Model1.Context.cs file I have chnaged the constructor to

public AdventureWorksEntities(string str)
        : base("name=AdventureWorksEntities")
    {
        this.Database.Connection.ConnectionString = str;
    }

and in the program.cs file

EntityConnectionStringBuilder ecsb = new EntityConnectionStringBuilder();
        ecsb.Metadata = @"res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl";
        ecsb.Provider = @"System.Data.SqlClient";
        ecsb.ProviderConnectionString =
            @"data source=.\sqlexpress;initial catalog=AdventureWorks;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework";

        using (var ent = new AdventureWorksEntities(ecsb.ConnectionString))
        {
            Console.WriteLine(ent.Database.Connection.ConnectionString);
            var add = ent.Addresses;
            foreach (var ad in add)
            {
                Console.WriteLine(ad.City);
            }


        }
        Console.ReadKey();

Now it says metadata keyword not found. How to set connectionstring for entityframework at runtime?

解决方案

This is an example using standard .aspx login information to set the UserID and Password information in the connection string. No connection string settings are stored in the web.config or app.config file.

Modify the Model.Designer.cs page as follows:

public partial class Entities : ObjectContext
{
    #region Constructors


    public static string getConStrSQL(string UID,string PWD)
    {

        string connectionString = new System.Data.EntityClient.EntityConnectionStringBuilder
        {
            Metadata = "res://*",
            Provider = "System.Data.SqlClient",
            ProviderConnectionString = new System.Data.SqlClient.SqlConnectionStringBuilder
            {
                InitialCatalog = "your_database_name",
                DataSource = "your_server",
                IntegratedSecurity = false,
                UserID = UID,                
                Password = PWD,              
            }.ConnectionString
        }.ConnectionString;

        return connectionString;
    }

    /// <summary>
    /// Initialize a new Entities object.
    /// </summary>
    public Entities(string UID,string PWD)
        : base(getConStrSQL(UID,PWD), "Entities")
    {
        this.ContextOptions.LazyLoadingEnabled = true;
        OnContextCreated();
    }
    ......

Then in your code behind page:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Mvc;
using System.Web.Security;


public partial class views_html_form : System.Web.UI.Page
{
public void Page_Load()
{
    if (currentUser() == null)
    {
        HttpContext.Current.Response.Redirect("~/login.aspx");
    }
}
public static MembershipUser currentUser()
{
    MembershipUser currentUser = Membership.GetUser();
    return currentUser;
}

public static string UID()
{
    string UID = currentUser().UserName;
    return UID;
}
public static string PWD()
{
    string PWD = currentUser().GetPassword();
    return PWD;
}
public static void SelectRecord()
{
    YourModel.Entities db = new YourModel.Entities(UID(), PWD());
    var query = from rows in db.Table_Name orderby rows.ID select rows;
   .....

That's it. No messing around with .config files. Alternatively you could send a database name, for example, as a parameter in the same way.

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

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