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

    }    

  • 相关阅读:
    合并果子
    在线最小值问题
    沙盒机制(sandBox)
    简单地址簿?
    浅拷贝、深拷贝
    NSFileManager、NSFileHandle
    NSDate、NSCalendar、NSDateFormatter
    归档
    类目、延展、协议
    动态类型
  • 原文地址:https://www.cnblogs.com/hgmyz/p/12352254.html
Copyright © 2020-2023  润新知