我有contained database user。由于它包含在数据库中,因此不允许连接到任何其他数据库,包括master。不幸的是,Entity Framework似乎无论如何都要连接到master数据库。
我已经使用最新的Entity Framework nuget(6.2.0)创建了一个新的控制台应用程序,以确保没有其他任何内容连接到master数据库:
static void Main(string[] args)
{
var connectionString = "Server=sql-azure.database.windows.net;Database='Database';User ID=Username;Password=password;Trusted_Connection=False;";
using (var dbContext = new DbContext(connectionString))
{
dbContext.Database.CommandTimeout = 10 * 60;
dbContext.Database.ExecuteSqlCommand("EXEC cleanup @Date", new SqlParameter("@Date", DateTime.UtcNow.AddMonths(-3)));
}
}
如何强制Entity Framework不连接到master数据库?我在master数据库的审计日志中出现故障,导致azure威胁检测结束。
答案 0 :(得分:0)
我无法重复:
包含用户:
//create user joe with password ='xxxxxx'
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Data.SqlClient;
using System.Linq;
namespace Ef6Test
{
class Program
{
static void Main(string[] args)
{
var connectionString = "server=xxxxxxxxx.database.windows.net;database=adventureworks;uid=joe;pwd=xxxx";
using (var dbContext = new DbContext(connectionString))
{
dbContext.Database.CommandTimeout = 10 * 60;
Console.WriteLine(dbContext.Database.SqlQuery<string>("select db_name() dbname;").Single());
}
Console.WriteLine("Hit any key to exit");
Console.ReadKey();
}
}
}
答案 1 :(得分:0)
在研究了一些之后,我在使用语句之前禁用了数据库初始化程序,如下所示:
Database.SetInitializer<DbContext>(null);
使用这行代码,控制台应用程序不再连接到master数据库。 More info about Database.SetInitializer(null)
完整示例:
static void Main(string[] args)
{
var connectionString = "Server=sql-azure.database.windows.net;Database='Database';User ID=Username;Password=password;Trusted_Connection=False;";
Database.SetInitializer<DbContext>(null);
using (var dbContext = new DbContext(connectionString))
{
dbContext.Database.CommandTimeout = 10 * 60;
dbContext.Database.ExecuteSqlCommand("EXEC cleanup @Date", new SqlParameter("@Date", DateTime.UtcNow.AddMonths(-3)));
}
}
答案 2 :(得分:0)
以下内容适用于本地MS SQL,以及您是否使用SQL Azure:
use master;
CREATE LOGIN DemoUser WITH PASSWORD = 'DemoPassword';
GO
CREATE USER DemoUser FOR LOGIN DemoUser
GO
use DemoDB;
CREATE USER DemoUser FOR LOGIN DemoUser WITH DEFAULT_SCHEMA=[dbo]
GO
ALTER ROLE db_datareader ADD MEMBER DemoUser;
ALTER ROLE db_datawriter ADD MEMBER DemoUser;