C# 根据ADO.NET数据库连接字符串构建EntityFrame数据库连接字符串

为了保持开发效率,以及保持代码优雅,项目中引用了EntityFrame。但是又因为某些报表功能需要大量计算,所以又要求直接使用ADO.NET,调用存储过程进行计算。

于是乎webconfig文件中就会出现两种数据库连接字符串。

<!--EntityFrame-->
<connectionStrings>
<add name="GpsDBEntities" connectionString="metadata=res://*/Models.DbModels.XXXX.csdl|res://*/Models.DbModels.XXXX.ssdl|res://*/Models.DbModels.XXXX.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=XXXXX;initial catalog=XXXXX;persist security info=True;user id=XXXX;password=XXXXX;MultipleActiveResultSets=True;App=EntityFramework&quot;"providerName="System.Data.EntityClient" />
</connectionStrings>
<!--ADO.NET-->
<add key="sqlConnectionString" value="server=XXXXX;uid=XXXXX;pwd=XXXX;database=XXXX"></add>

可以这样写又显得累赘,为什么同一个数据库,我要写两次连接字符串。

于是想只保留ADO.NET的数据库连接字符串,在使用EntityFrame的时候,生产EntityFrame专用的数据库连接字符串进行连接。

因此我构建了一个工具类,用来生成EntityFrame的数据库连接字符串。

public sealed class DBConnectionUtil
{
private static string IP { get; set; }
private static string UserId { get; set; }
private static string Password { get; set; }
private static string DBName { get; set; }
public static string EntityConnectionStr { get; set; } public static readonly DBConnectionUtil instance = new DBConnectionUtil();
private DBConnectionUtil()
{
GetDBSetting();
} private void GetDBSetting(){
var connectStr = ConfigurationManager.AppSettings["sqlConnectionString"];
var settingArray = connectStr.Split(';');
foreach (var setting in settingArray)
{
var keyVal = setting.Split('=');
switch (keyVal[])
{
case "server": IP = keyVal[]; break;
case "uid": UserId = keyVal[]; break;
case "pwd": Password = keyVal[]; break;
case "database": DBName = keyVal[]; break;
}
} EntityConnectionStr = "metadata=res://*/Models.DbModels.GpsDB.csdl|res://*/Models.DbModels.GpsDB.ssdl|res://*/Models.DbModels.GpsDB.msl;provider=System.Data.SqlClient;provider connection string=\"data source=" + IP + ";initial catalog=" + DBName + ";persist security info=True;user id=" + UserId + ";password=" + Password + ";MultipleActiveResultSets=True;App=EntityFramework\"";
}
}

然后在使用时直接调用即可。

public partial class XXXXX : DbContext
{
public XXXXX()
: base(DBConnectionUtil.EntityConnectionStr)
{
} protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
}
上一篇:Java:回调机制


下一篇:Git的安装配置(win环境)