/// <summary> /// 获取指定数据上下文类型<typeparamref name="TEntity"/>的实例,并将同数据库连接字符串的上下文实例进行分组归类 /// </summary> /// <typeparam name="TEntity">实体类型</typeparam> /// <typeparam name="TKey">实体主键类型</typeparam> /// <returns><typeparamref name="TEntity"/>所属上下文类的实例</returns> public IDbContext GetDbContext <TEntity, TKey>() where TEntity : IEntity <TKey> where TKey : IEquatable <TKey> { IEntityConfigurationTypeFinder typeFinder = _serviceProvider.GetService <IEntityConfigurationTypeFinder>(); Type entityType = typeof(TEntity); Type dbContextType = typeFinder.GetDbContextTypeForEntity(entityType); OSharpDbContextOptions dbContextOptions = GetDbContextResolveOptions(dbContextType); DbContextResolveOptions resolveOptions = new DbContextResolveOptions(dbContextOptions); //已存在上下文对象,直接返回 DbContextBase dbContext = _dbContextMamager.Get(dbContextType, resolveOptions.ConnectionString); if (dbContext != null) { return(dbContext); } IDbContextResolver contextResolver = _serviceProvider.GetService <IDbContextResolver>(); dbContext = (DbContextBase)contextResolver.Resolve(resolveOptions); if (!dbContext.ExistsRelationalDatabase()) { throw new OsharpException($"数据上下文“{dbContext.GetType().FullName}”的数据库不存在,请通过 Migration 功能进行数据迁移创建数据库。"); } if (resolveOptions.ExistingConnection == null) { resolveOptions.ExistingConnection = dbContext.Database.GetDbConnection(); } _dbContextMamager.Add(dbContextOptions.ConnectionString, dbContext); return(dbContext); }