我的配置具有带有加密密码的连接字符串。代码使用的是Entity Framework System.Data.Entity.DbContext,其中包含加密的密码。
如何自定义System.Data.Entity.DbContext.Database.Connection.ConnectionString以使用解密的密码。

下面的代码DrcMaster抛出错误:登录失败(因为它试图使用加密密码)

using System;
using System.Data.Entity;
using System.Configuration;

namespace DrcAuthentication.Database.User {
    public class UserContext : DbContext
    {
        public UserContext()
        {
            System.Data.SqlClient.SqlConnectionStringBuilder csb = new System.Data.SqlClient.SqlConnectionStringBuilder(ConfigurationManager.ConnectionStrings["UserContext"].ConnectionString.ToString());
            csb.Password = EncryptionUtils.Decrypt(csb.Password);
            string myCs = csb.ToString();
            Database.Connection.ConnectionString = myCs;
            //db.Database.Connection.ConnectionString = myCs;
            this.Configuration.LazyLoadingEnabled = false;
            this.Configuration.ProxyCreationEnabled = false;
        }

        public DbSet<DrcAuthentication.DrcMaster> DrcMasters { get; set; }
        public DbSet<DrcAuthentication.AuthenticatedUser> Users { get; set; }
        public DbSet<DrcAuthentication.UserRole> UserRoles { get; set; }
        //public IDbSet<SuperSecured> SuperSecured { get; set; }
    }
}

最佳答案

不要使用Database.Connection.ConnectionString设置连接字符串。 DbContext类具有一个接受连接字符串的构造函数。您可以将获取连接字符串的逻辑移动并将其解密为静态方法,然后从DbContext的构造函数构造基类UserContext,如下所示:

public class UserContext : DbContext
{
    public static string GetConnectionString()
    {
        System.Data.SqlClient.SqlConnectionStringBuilder csb = new System.Data.SqlClient.SqlConnectionStringBuilder(ConfigurationManager.ConnectionStrings["UserContext"].ConnectionString.ToString());
        csb.Password = EncryptionUtils.Decrypt(csb.Password);
        string myCs = csb.ToString();
        return myCs;
    }

    public UserContext()
        :base(GetConnectionString())
    {
        this.Configuration.LazyLoadingEnabled = false;
        this.Configuration.ProxyCreationEnabled = false;
    }



    public DbSet<DrcAuthentication.DrcMaster> DrcMasters { get; set; }
    public DbSet<DrcAuthentication.AuthenticatedUser> Users { get; set; }
    public DbSet<DrcAuthentication.UserRole> UserRoles { get; set; }
    //public IDbSet<SuperSecured> SuperSecured { get; set; }

}


但是,我建议不要这样做,而是将获取和解密连接字符串的责任移到另一个类。这使得UserContext类像这样:

public class UserContext : DbContext
{
    public UserContext(string connection_string)
        :base(connection_string)
    {
        this.Configuration.LazyLoadingEnabled = false;
        this.Configuration.ProxyCreationEnabled = false;
    }

    public DbSet<DrcAuthentication.DrcMaster> DrcMasters { get; set; }
    public DbSet<DrcAuthentication.AuthenticatedUser> Users { get; set; }
    public DbSet<DrcAuthentication.UserRole> UserRoles { get; set; }
    //public IDbSet<SuperSecured> SuperSecured { get; set; }

}


然后,另一个类会将解密后的连接字符串注入到UserContext类中。

09-25 19:54
查看更多