Entity framework 为具有DbContextScope项目的查询指定连接字符串
我现在正在使用,我觉得是书上说的,它很棒。但我今天遇到了一个问题,我不知道该如何解决。我需要使用不同的数据库登录名/用户执行一个查询,因为它需要额外的权限。我可以在我的web.config中创建另一个连接字符串,但我不确定如何为此查询指定,我想使用这个新的连接字符串。以下是我的用法: 在我的逻辑层:Entity framework 为具有DbContextScope项目的查询指定连接字符串,entity-framework,connection-string,dbcontext,Entity Framework,Connection String,Dbcontext,我现在正在使用,我觉得是书上说的,它很棒。但我今天遇到了一个问题,我不知道该如何解决。我需要使用不同的数据库登录名/用户执行一个查询,因为它需要额外的权限。我可以在我的web.config中创建另一个连接字符串,但我不确定如何为此查询指定,我想使用这个新的连接字符串。以下是我的用法: 在我的逻辑层: private static IDbContextScopeFactory _dbContextFactory = new DbContextScopeFactory(); public stat
private static IDbContextScopeFactory _dbContextFactory = new DbContextScopeFactory();
public static Guid GetFacilityID(string altID)
{
...
using (_dbContextFactory.CreateReadOnly())
{
entity = entities.GetFacilityID(altID)
}
}
这将调用我的数据层,看起来像这样:
private AmbientDbContextLocator _dbcLocator = new AmbientDbContextLocator();
protected CRMEntities DBContext
{
get
{
var dbContext = _dbcLocator.Get<CRMEntities>();
if (dbContext == null)
throw new InvalidOperationException("No ambient DbContext....");
return dbContext;
}
}
public virtual Guid GetFaciltyID(string altID)
{
return DBContext.Set<Facility>().Where(f => f.altID = altID).Select(f => f.ID).FirstOrDefault();
}
这个特定的查询是否可能使用不同的连接字符串以及如何使用?我最终以一种让人感觉有点不舒服的方式修改了源代码,但现在正在完成这项工作。我创建了一个新的IAmbientDbContextLocator,它具有接受连接字符串的Get方法覆盖:
public TDbContext Get<TDbContext>(string nameOrConnectionString) where TDbContext : DbContext
{
var ambientDbContextScope = DbContextScope.GetAmbientScope();
return ambientDbContextScope == null ? null : ambientDbContextScope.DbContexts.Get<TDbContext>(nameOrConnectionString);
}
当然,您必须小心,您的代码不会在应该通过同一个上下文/连接字符串时通过两个不同的上下文/连接字符串。在我的例子中,我将它们分为两个不同的数据访问类实现。我认为这就是实现方法。您可以添加一个保护,即只有当上下文的数据库与上一项(如果存在)具有相同的连接字符串时,才会将上下文添加到字典中。
public TDbContext Get<TDbContext>(string nameOrConnectionString) where TDbContext : DbContext
{
var ambientDbContextScope = DbContextScope.GetAmbientScope();
return ambientDbContextScope == null ? null : ambientDbContextScope.DbContexts.Get<TDbContext>(nameOrConnectionString);
}
var dbContext = new CustomAmbientDbContextLocator().Get<CRMEntities>("name=CRMEntitiesAdmin");