Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/330.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在代码中将凭据(用户名/密码)分配给EF_C#_Entity Framework - Fatal编程技术网

C# 在代码中将凭据(用户名/密码)分配给EF

C# 在代码中将凭据(用户名/密码)分配给EF,c#,entity-framework,C#,Entity Framework,我已经设置了实体模型和连接,您可能知道,当您将连接设置为存储在配置文件中时,它建议您不要将“敏感”数据(即用户名和密码)存储在配置文件中,我想做的是允许用户自己输入该信息 如何在代码中将其分配给连接 我必须拉取字符串,修改它(通过添加用户/通行证),然后重新分配连接字符串吗?听起来像桌面(不是web应用程序),对吗?既然您可能不是在internet上运行,而是在本地网络上运行,为什么不使用集成(windows)安全性而不是sql server安全性,并且必须存储登录名/密码。我根本没有想到这一点

我已经设置了实体模型和连接,您可能知道,当您将连接设置为存储在配置文件中时,它建议您不要将“敏感”数据(即用户名和密码)存储在配置文件中,我想做的是允许用户自己输入该信息

如何在代码中将其分配给连接


我必须拉取字符串,修改它(通过添加用户/通行证),然后重新分配连接字符串吗?

听起来像桌面(不是web应用程序),对吗?既然您可能不是在internet上运行,而是在本地网络上运行,为什么不使用集成(windows)安全性而不是sql server安全性,并且必须存储登录名/密码。

我根本没有想到这一点。听起来不错。我将试一试,看看效果如何。在intranet场景中,集成安全性是首选的身份验证方法。(现在我听起来像个顾问)
public class MyContext : DbContext
{
    // Add a constructor that takes a connection string
    public MyContext(string connString)
        : base(connString)
    {         
    }
}

// Call this method from a page or controller
public void ConnectToTheDatabase(string username, string password)
{
    // create the connection string; I like to user the builder
    System.Data.Common.DbConnectionStringBuilder builder 
        = new System.Data.Common.DbConnectionStringBuilder();

    builder.Add("Server", "tcp:asdfewsdfgwe.database.windows.net,1422");
    builder.Add("Database", "supersonic_db");
    builder.Add("User ID", username);
    builder.Add("Password", password);
    builder.Add("Trusted_Connection", "False");
    builder.Add("Encrypt", "True");
    builder.Add("Connection Timeout", "30");

    var connString = builder.ToString();

    // Set the connection string
    MyContext context = new MyContext(connString);

    // Test with something simple
    context.Database.Connection.Open();
    string version = context.Database.Connection.ServerVersion;
    version = version.ToUpper();
}