您可以使用SQL Server SMO以編程方式創建數據庫用戶,並在您的EF代碼優先DatabaseInitializer
中第一次添加它。儘管如此,請謹慎使用;)
添加引用以下內容。
Microsoft.SqlServer.ConnectionInfo
Microsoft.SqlServer.Smo
Microsoft.SqlServer.SqlEnum
然後創建一個SQL登錄,也將用戶添加到您的目標數據庫源代碼的
var serverName = "."; // Your SQL Server Instance name
var databaseName = "Test"; // Your database name
var loginName = "testuserY"; // Your login name (should not exist - or you should add code to check if the login exists)
Server svr = new Server(serverName);
var db = svr.Databases[databaseName];
if (db != null)
{
// You probably want to create a login and add as a user to your database
Login login = new Login(svr, loginName);
login.DefaultDatabase = "master"; // Logins typically have master as default database
login.LoginType = LoginType.SqlLogin;
login.Create("foobar", LoginCreateOptions.None); // Enter a suitable password
login.Enable();
User user = new User(db, loginName);
user.UserType = UserType.SqlLogin;
user.Login = login.Name;
user.Create();
// add a role
user.AddToRole("db_owner");
}
來源:https://stackoverflow.com/a/7899436/325521
對不起,我是初學者,我在哪裏可以把這個代碼? – Lai32290