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

    }    

  • 相关阅读:
    windows测试模式
    架构设计之Spring-Session的分布式集群会话管理
    WPF集合
    java Socket Udp
    java Socket 获取本地主机ip
    快速排序
    java 正则举例
    JNI 在命令行窗口输入字符,不显所输入字符,显指定的掩饰符
    java 在控制台上输入密码时,密码不显示在控制台上
    java 获取对象大小
  • 原文地址:https://www.cnblogs.com/hgmyz/p/12352255.html
Copyright © 2020-2023  润新知