代码之家  ›  专栏  ›  技术社区  ›  xr280xr

使用DbContextScope项目指定查询的连接字符串

  •  0
  • xr280xr  · 技术社区  · 8 年前

    我目前正在使用 Mehdi El Gueddari's DbContextScope project

    在我的逻辑层:

    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();
        }
    

    当前,我的连接字符串以默认方式设置:

    public partial class CRMEntities : DbContext
    {
        public CRMEntities()
            : base("name=CRMEntities")
        {}
    }
    

    这个特定的查询是否可以使用不同的连接字符串,以及如何使用?

    1 回复  |  直到 8 年前
        1
  •  1
  •   xr280xr    7 年前

    我最终以一种感觉有点粗糙的方式修改了源代码,但目前正在完成这项工作。我创建了一个新的 IAmbientDbContextLocator Get<TDbContext> 接受连接字符串的方法重写:

        public TDbContext Get<TDbContext>(string nameOrConnectionString) where TDbContext : DbContext
        {
            var ambientDbContextScope = DbContextScope.GetAmbientScope();
            return ambientDbContextScope == null ? null : ambientDbContextScope.DbContexts.Get<TDbContext>(nameOrConnectionString);
        }
    

    然后我更新了 DbContextCollection 将此参数传递给 DbContext 维护 Dictionary<KeyValuePair<Type, string>, DbContext> 而不是 Dictionary<Type, DbContext> 作为其缓存 _initializedDbContexts 其中添加了 string nameOrConnectionString 参数。换句话说,我将其更新为cache unique 数据库上下文

    然后我可以到达 数据库上下文

    var dbContext = new CustomAmbientDbContextLocator().Get<CRMEntities>("name=CRMEntitiesAdmin");
    

    当然,当代码应该通过同一个上下文/连接字符串时,您必须小心不要通过两个不同的上下文/连接字符串。在我的例子中,我将它们分为两个不同的数据访问类实现。