简体   繁体   中英

Connecting multiple sql users to one database with entity framework

Hello i am a beginner in C# winform, I have to connect multiple users (400 different users) through a login form ( textbox : name - password) to a single sql database with Winform C#, all users are sql users created in the database and have roles like users or admin. I have been looking for an easy way of doing this with entity framework but couldn't find anyhting.. anyone has an idea how this can be done ? Thanks for your help.

Does every user need their own login to the database?

If this is true you would need to write a special connection string, something like below:

using System.Data.SqlClient;

SqlConnection conn = new SqlConnection();
conn.ConnectionString =
    "Data Source=ServerName;" +
    "Initial Catalog=DataBaseName;" +
    "User id=" + UserName + ";"
    "Password=" + Password + ";";
 conn.Open();

Put this in a class that accepts the username and password.

Full example:

class myConnection
{
    public static SqlConnection GetConnection(string UserName, string Password)
    {
        string str = "Data Source=ServerName;Initial Catalog=DataBaseName;User id=" + UserName + ";Password=" + Password + ";";
        SQlConnection con = new SqlConnection(str);
        con.Open();
        return con;
    }
}

User credentials are specified in the connection string, so you need to build a connection string with the data provided by the user in the login form.

var sqlBuilder = new SqlConnectionStringBuilder();

// Set the properties for the data source.
sqlBuilder.DataSource = "ServerName";
sqlBuilder.InitialCatalog = "DatabaseName";

sqlBuilder.UserID = "USERNAME";
sqlBuilder.Password = "PASSWORD";

sqlBuilder.IntegratedSecurity = true;

// Build the SqlConnection connection string.
string providerString = sqlBuilder.ToString();

// Initialize the EntityConnectionStringBuilder.
var entityBuilder = new EntityConnectionStringBuilder();

//Set the provider name.
entityBuilder.Provider = "System.Data.SqlClient";

// Set the provider-specific connection string.
entityBuilder.ProviderConnectionString = providerString;

And then use this connection string to initialize your DbContext

var context = new DbContext(entityBuilder.ConnectionString);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM