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