EF 实现自定义数据库字符串

Scroll Down

Csharp.png

1、EF模板生成继承DbContext的类文件重新建一个部分类文件

避免每次生成实体都会覆盖掉。

2、重新构造调用数据库连接字符串的函数

VS模板生成示例:

public Test_DBEntities()

: base("name=Test_DBEntities")

{

}    

重写函数

public Test_DBEntities(string connectionString)

: base(connectionString)

{

}  

3、自定义EF数据库字符串函数(SQLServer)

public static string GetConnection()
{

string DataSource = ".";

string DataBase = "DB;

string UserId = "sa";

string PassWord = "sa";

SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder();

sqlBuilder.DataSource = DataSource;

sqlBuilder.InitialCatalog = DataBase;

sqlBuilder.PersistSecurityInfo = true;

sqlBuilder.IntegratedSecurity = true;

sqlBuilder.MultipleActiveResultSets = true;

sqlBuilder.UserID = UserId;

sqlBuilder.Password = PassWord;

EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();

entityBuilder.ProviderConnectionString = sqlBuilder.ToString();

entityBuilder.Metadata = "res://*/";

entityBuilder.Provider = "System.Data.SqlClient";

return entityBuilder.ToString();

}  

4、调用示例

 string definestr = "";//自定义数据库查询结果

string str = "";

using (var db = new Test_DBEntities())

{

var list = db.T_User.Select(m=>m.name).ToList();

str= string.Join(",", list);

}

using (var db = new Test_DBEntities(ConnectionHelper.GetConnection()))

{

var list = db.T_User.Select(m => m.name).ToList();

definestr = string.Join(",", list);

}    

EF 实现自定义数据库字符串