1

我已经从 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;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();

现在它说找不到元数据关键字。如何在运行时为实体框架设置连接字符串?

4

2 回答 2

7

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

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

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

然后在页面后面的代码中:

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;
   .....

而已。不要乱用 .config 文件。或者,您可以发送数据库名称,例如,以相同方式作为参数。

于 2013-08-13T11:02:31.570 回答
2

我会选择类似的东西:

 public AdventureWorksEntities(string server, string databaseName, string user, string password)
        :base(new System.Data.EntityClient.EntityConnectionStringBuilder
        {
            Metadata = "res://*",
            Provider = "System.Data.SqlClient",
            ProviderConnectionString = new System.Data.SqlClient.SqlConnectionStringBuilder 
            {
                InitialCatalog = databaseName,
                DataSource = server,
                IntegratedSecurity = false,
                UserID = user,
                Password = password,

            }.ConnectionString
        }.ConnectionString) 
    {

    }
于 2014-01-15T15:25:09.003 回答