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

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

作者:互联网

4418040-88555306818d5414


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

}    

标签:sqlBuilder,string,自定义,数据库,EF,db,entityBuilder,Test,DBEntities
来源: https://blog.51cto.com/u_11205641/2829705