How to create a Database user in Entity Framework entity-framework entity-framework-6 sql-server


Been working on my first Entity Framework project. As part of the project I am going to be creating a number of SSRS reports. In order to connect to the database I need to have a Reports user that will only access to the specific database on the server. In the past i have always written a script to add Database users but I want to know is there a way that i can do this using Entity Framework instead?

9/14/2017 9:20:24 PM

Accepted Answer

You would need to tell EF to use the appropriate stored procedures to do so. You could also wrap these up in a sproc of your own that wraps the relevant commands. There is no native "CreateReportsUser" type method within EF that I know of.

Edit: I probably should have provided this reference to be a "complete" answer. Apologies.

Here's how you can do what I recommend: How to call Stored Procedure in Entity Framework 6 (Code-First)?

5/23/2017 12:33:53 PM

Popular Answer

Assuming your user already has a login defined at the SQL Server level (Security > Logins), you can call the following method from your DB initializer seed method to add the user to the database:

private void AddDbUser(MyDataContext myDB)
    string accountDomainName = "AccountDomainName";  // replace with user's login domain
    string accountLoginID = "AccountLoginID";  // replace with user's login ID

    string sql = 
        "USE [MyDB]" +
        "CREATE USER [MyNewUser] FOR LOGIN [" + accountDomainName + "\\" + accountLoginID + "]" +
        "ALTER AUTHORIZATION ON SCHEMA::[db_datareader] TO [" + accountLoginID + "]" +
        "ALTER AUTHORIZATION ON SCHEMA::[db_datawriter] TO [" + accountLoginID + "]" +
        "EXEC sp_addrolemember N'db_datawriter', N'" + accountLoginID + "'" +
        "EXEC sp_addrolemember N'db_datareader', N'" + accountLoginID + "'";


The exact SQL needed may vary. To generate the SQL for your scenario, you could open the add user dialog in SSMS (Database > Users > New User...), fill out the fields, and click the "Script" button at the top instead of hitting OK at the bottom. Note that any "GO" lines will need to be removed from the generated script before pasting it into the method above.

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow