Exemplo n.º 1
0
        /// <summary>
        /// 应用模块服务
        /// </summary>
        /// <param name="provider">服务提供者</param>
        public override void UsePack(IServiceProvider provider)
        {
            IEntityConfigurationTypeFinder finder = provider.GetService <IEntityConfigurationTypeFinder>();

            finder?.Initialize();
            IsEnabled = true;
        }
Exemplo n.º 2
0
        /// <summary>
        /// 获取指定实体所在的工作单元对象
        /// </summary>
        /// <param name="entityType">实体类型</param>
        /// <returns>工作单元对象</returns>
        public IUnitOfWork GetUnitOfWork(Type entityType)
        {
            if (!entityType.IsEntityType())
            {
                throw new OsharpException($"类型“{entityType}”不是实体类型");
            }
            IUnitOfWork unitOfWork = _entityTypeUnitOfWorks.GetOrDefault(entityType);

            if (unitOfWork != null)
            {
                return(unitOfWork);
            }
            IEntityConfigurationTypeFinder typeFinder = _serviceProvider.GetService <IEntityConfigurationTypeFinder>();
            Type dbContextType = typeFinder.GetDbContextTypeForEntity(entityType);

            if (dbContextType == null)
            {
                throw new OsharpException($"实体类“{entityType}”的所属上下文类型无法找到");
            }
            OSharpDbContextOptions  dbContextOptions = GetDbContextResolveOptions(dbContextType);
            DbContextResolveOptions resolveOptions   = new DbContextResolveOptions(dbContextOptions);

            unitOfWork = _connStringUnitOfWorks.GetOrDefault(resolveOptions.ConnectionString);
            if (unitOfWork != null)
            {
                return(unitOfWork);
            }
            unitOfWork = ActivatorUtilities.CreateInstance <UnitOfWork>(_serviceProvider, resolveOptions);
            _entityTypeUnitOfWorks.TryAdd(entityType, unitOfWork);
            _connStringUnitOfWorks.TryAdd(resolveOptions.ConnectionString, unitOfWork);

            return(unitOfWork);
        }
        /// <summary>
        /// 应用模块服务
        /// </summary>
        /// <param name="app">应用程序构建器</param>
        public override void UsePack(IApplicationBuilder app)
        {
            IEntityConfigurationTypeFinder finder = app.ApplicationServices.GetService <IEntityConfigurationTypeFinder>();

            finder?.Initialize();
            IsEnabled = true;
        }
Exemplo n.º 4
0
 public DbContextFactory(
     EntityFrameworkOptionsCollection optionsCollection, IServiceProvider serviceProvider)
 {
     _entityConfigurationTypeFinder = serviceProvider.GetRequiredService <IEntityConfigurationTypeFinder>();
     _serviceProvider   = serviceProvider;
     _optionsCollection = optionsCollection;
 }
Exemplo n.º 5
0
        /// <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);
        }
Exemplo n.º 6
0
        /// <summary>
        /// 获取指定数据实体的上下文类型
        /// </summary>
        /// <param name="entityType">实体类型</param>
        /// <returns>实体所属上下文实例</returns>
        public IDbContext GetDbContext(Type entityType)
        {
            if (!entityType.IsEntityType())
            {
                throw new OsharpException($"类型“{entityType}”不是实体类型");
            }

            IEntityConfigurationTypeFinder typeFinder = _serviceProvider.GetService <IEntityConfigurationTypeFinder>();
            Type dbContextType = typeFinder.GetDbContextTypeForEntity(entityType);

            //已存在上下文对象,直接返回
            DbContextBase dbContext = _dbContexts.FirstOrDefault(m => m.GetType() == dbContextType);

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

            dbContext.UnitOfWork = this;
            _dbContexts.Add(dbContext);

            return(dbContext);
        }
Exemplo n.º 7
0
        /// <summary>
        /// 初始化一个<see cref="DbContextBase"/>类型的新实例
        /// </summary>
        protected DbContextBase(DbContextOptions options, IEntityConfigurationTypeFinder typeFinder)
            : base(options)
        {
            _typeFinder = typeFinder;
            IOptions <OSharpOptions> osharpOptions = this.GetService <IOptions <OSharpOptions> >();

            _osharpDbOptions = osharpOptions?.Value.DbContexts.Values.FirstOrDefault(m => m.DbContextType == GetType());
            _logger          = this.GetService <ILoggerFactory>().CreateLogger(GetType());
        }
        /// <summary>
        /// 创建一个数据上下文实例
        /// </summary>
        /// <param name="args">参数</param>
        /// <returns></returns>
        public virtual TDbContext CreateDbContext(string[] args)
        {
            string connString = GetConnectionString();
            IEntityConfigurationTypeFinder typeFinder = GetEntityConfigurationTypeFinder();
            DbContextOptionsBuilder        builder    = new DbContextOptionsBuilder <TDbContext>();

            builder = UseSql(builder, connString);
            return((TDbContext)Activator.CreateInstance(typeof(TDbContext), builder.Options, typeFinder));
        }
Exemplo n.º 9
0
        /// <summary>
        /// 初始化一个<see cref="DbContextBase{TDbContext}"/>类型的新实例
        /// </summary>
        protected DbContextBase(DbContextOptions options, IEntityConfigurationTypeFinder typeFinder)
            : base(options)
        {
            _typeFinder = typeFinder;
            IOptionsMonitor <OSharpOptions> osharpOptions = ServiceLocator.Instance.GetService <IOptionsMonitor <OSharpOptions> >();

            if (osharpOptions != null)
            {
                _osharpDbOptions = osharpOptions.CurrentValue.DbContextOptionses.Values.FirstOrDefault(m => m.DbContextType == typeof(TDbContext));
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// 初始化一个<see cref="DbContextBase"/>类型的新实例
        /// </summary>
        protected DbContextBase(DbContextOptions options, IEntityConfigurationTypeFinder typeFinder)
            : base(options)
        {
            _typeFinder = typeFinder;
            if (ServiceLocator.Instance.IsProviderEnabled)
            {
                IOptions <OSharpOptions> osharpOptions = ServiceLocator.Instance.GetService <IOptions <OSharpOptions> >();
                _osharpDbOptions = osharpOptions?.Value.DbContextOptionses.Values.FirstOrDefault(m => m.DbContextType == GetType());

                _logger = ServiceLocator.Instance.GetLogger(GetType());
            }
        }
Exemplo n.º 11
0
 /// <summary>
 /// 初始化一个<see cref="DbContextBase"/>类型的新实例
 /// </summary>
 protected DbContextBase(
     DbContextOptions options,
     IEntityConfigurationTypeFinder typeFinder,
     IEventBus eventBus,
     ILoggerFactory loggerFactory)
     : base(options)
 {
     _typeFinder    = typeFinder;
     _loggerFactory = loggerFactory;
     _logger        = loggerFactory?.CreateLogger(GetType());
     _eventBus      = eventBus;
 }
Exemplo n.º 12
0
        /// <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);

            DbContext dbContext;
            OSharpDbContextOptions  dbContextOptions = GetDbContextResolveOptions(dbContextType);
            DbContextResolveOptions resolveOptions   = new DbContextResolveOptions(dbContextOptions);
            IDbContextResolver      contextResolver  = _serviceProvider.GetService <IDbContextResolver>();
            ActiveTransactionInfo   transInfo        = ActiveTransactionInfos.GetOrDefault(resolveOptions.ConnectionString);

            //连接字符串的事务不存在,添加起始上下文事务信息
            if (transInfo == null)
            {
                resolveOptions.ExistingConnection = null;
                dbContext = contextResolver.Resolve(resolveOptions);
                RelationalDatabaseCreator dbCreator;
                if ((dbCreator = dbContext.GetService <IDatabaseCreator>() as RelationalDatabaseCreator) != null)
                {
                    if (!dbCreator.Exists())
                    {
                        throw new OsharpException($"数据上下文“{dbContext.GetType().FullName}”的数据库不存在,请通过 Migration 功能进行数据迁移创建数据库。");
                    }
                }
                IDbContextTransaction transaction = dbContext.Database.BeginTransaction();
                transInfo = new ActiveTransactionInfo(transaction, dbContext);
                ActiveTransactionInfos[resolveOptions.ConnectionString] = transInfo;
            }
            else
            {
                resolveOptions.ExistingConnection = transInfo.DbContextTransaction.GetDbTransaction().Connection;
                //相同连接串相同上下文类型并且已存在对象,直接返回上下文对象
                if (transInfo.StarterDbContext.GetType() == resolveOptions.DbContextType)
                {
                    return(transInfo.StarterDbContext as IDbContext);
                }
                dbContext = contextResolver.Resolve(resolveOptions);
                if (dbContext.IsRelationalTransaction())
                {
                    dbContext.Database.UseTransaction(transInfo.DbContextTransaction.GetDbTransaction());
                }
                else
                {
                    dbContext.Database.BeginTransaction();
                }
                transInfo.AttendedDbContexts.Add(dbContext);
            }
            return(dbContext as IDbContext);
        }
Exemplo n.º 13
0
        /// <summary>
        /// 创建上下文数据模型时,对各个实体类数据库映射配置
        /// </summary>
        /// <param name="modelBuilder"></param>
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            IEntityConfigurationTypeFinder entityConfigurationTypeFinder = _serviceProvider.GetService <IEntityConfigurationTypeFinder>();

            Type[] types = entityConfigurationTypeFinder.FindAll(true);

            if (types.Length == 0)
            {
                return;
            }

            List <IEntityRegister> registers =
                types.Select(type => Activator.CreateInstance(type) as IEntityRegister).ToList();

            foreach (var entityRegister in registers)
            {
                entityRegister.RegisterTo(modelBuilder);
            }
        }
Exemplo n.º 14
0
        /// <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 dbContextType = typeFinder.GetDbContextTypeForEntity(typeof(TEntity));

            DbContext               dbContext;
            OsharpDbContextConfig   dbContextConfig = GetDbContextResolveOptionsConfig(dbContextType);
            DbContextResolveOptions resolveOptions  = new DbContextResolveOptions(dbContextConfig);
            IDbContextResolver      contextResolver = _serviceProvider.GetService <IDbContextResolver>();
            ActiveTransactionInfo   transInfo       = ActiveTransactionInfos.GetOrDefault(resolveOptions.ConnectionString);

            //连接字符串的事务不存在,添加起始上下文事务信息
            if (transInfo == null)
            {
                resolveOptions.ExistingConnection = null;
                dbContext = contextResolver.Resolve(resolveOptions);
                IDbContextTransaction transaction = dbContext.Database.BeginTransaction();
                transInfo = new ActiveTransactionInfo(transaction, dbContext);
                ActiveTransactionInfos[resolveOptions.ConnectionString] = transInfo;
            }
            else
            {
                resolveOptions.ExistingConnection = transInfo.DbContextTransaction.GetDbTransaction().Connection;
                dbContext = contextResolver.Resolve(resolveOptions);
                if (dbContext.IsRelationalTransaction())
                {
                    dbContext.Database.UseTransaction(transInfo.DbContextTransaction.GetDbTransaction());
                }
                else
                {
                    dbContext.Database.BeginTransaction();
                }
                transInfo.AttendedDbContexts.Add(dbContext);
            }
            return(dbContext as IDbContext);
        }
Exemplo n.º 15
0
 public DesignTimeDefaultDbContext(DbContextOptions options, IEntityConfigurationTypeFinder typeFinder)
     : base(options, typeFinder)
 {
 }
Exemplo n.º 16
0
 public MySqlDbContext(DbContextOptions options, IEntityConfigurationTypeFinder typeFinder) : base(options, typeFinder)
 {
 }
Exemplo n.º 17
0
 /// <summary>
 /// 初始化一个<see cref="EntityManager"/>类型的新实例
 /// </summary>
 public EntityManager(IEntityConfigurationTypeFinder typeFinder)
 {
     _typeFinder = typeFinder;
 }
Exemplo n.º 18
0
    /// <summary>
    /// 创建上下文数据模型时,对各个实体类的数据库映射细节进行配置
    /// </summary>
    /// <param name="modelBuilder">上下文数据模型构建器</param>
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        _entityConfigurationTypeFinder = this.GetService <IEntityConfigurationTypeFinder>();

        //通过实体配置信息将实体注册到当前上下文
        var contextType = GetType();

        var entityTypeConfigurations = _entityConfigurationTypeFinder.GetEntityTypeConfigurations(contextType);
        var count         = 0;
        var stringBuilder = new StringBuilder();

        foreach (var entityTypeConfiguration in entityTypeConfigurations)
        {
            entityTypeConfiguration.Value.MethodInfo.Invoke(modelBuilder,
                                                            new[] { entityTypeConfiguration.Value.EntityTypeConfiguration });

            stringBuilder.Append($"、{entityTypeConfiguration.Value.EntityType.FullName}");
            count++;
        }

        _logger.LogInformation(
            $"将 {count} 个实体 {stringBuilder} 注册到上下文 {contextType} 中");

        var option = _entityFrameworkOptions.Get(GetType());

        var tablePrefix = option.TablePrefix?.Trim();

        foreach (var entityType in modelBuilder.Model.GetEntityTypes())
        {
            if (!entityType.IsOwned())
            {
                var tableName = entityType.GetTableName();

                if (option.UseUnderScoreCase)
                {
                    tableName = tableName.ToSnakeCase();
                }

                if (!string.IsNullOrWhiteSpace(tablePrefix))
                {
                    tableName = tablePrefix + tableName;
                }

                entityType.SetTableName(tableName);
            }

            if (typeof(IDeletion).IsAssignableFrom(entityType.ClrType))
            {
                entityType.AddSoftDeleteQueryFilter();
            }

            var optimisticLockTable = typeof(IOptimisticLock).IsAssignableFrom(entityType.ClrType);
            var properties          = entityType.GetProperties();
            foreach (var property in properties)
            {
                if (optimisticLockTable &&
                    property.Name == "ConcurrencyStamp")
                {
                    property.SetMaxLength(36);
                    property.IsConcurrencyToken = true;
                    property.IsNullable         = true;
                }

                if (option.UseUnderScoreCase)
                {
                    var storeObjectIdentifier = StoreObjectIdentifier.Create(entityType, StoreObjectType.Table);
                    var propertyName          = property.GetColumnName(storeObjectIdentifier.GetValueOrDefault());
                    if (!string.IsNullOrEmpty(propertyName) && propertyName.StartsWith("_"))
                    {
                        propertyName = propertyName.Substring(1, propertyName.Length - 1);
                    }

                    property.SetColumnName(propertyName.ToSnakeCase());
                }

                if (property.ClrType == typeof(ObjectId))
                {
                    property.SetValueConverter(new ObjectIdToStringConverter());
                }
            }
        }
    }
Exemplo n.º 19
0
 /// <summary>
 /// 初始化一个<see cref="DefaultDbContext"/>类型的新实例
 /// </summary>
 public DefaultDbContext(DbContextOptions options, IEntityConfigurationTypeFinder typeFinder,
                         IEventBus eventBus,
                         ILoggerFactory loggerFactory)
     : base(options, typeFinder, eventBus, loggerFactory)
 {
 }
Exemplo n.º 20
0
 /// <summary>
 /// 初始化一个<see cref="DefaultDbContext"/>类型的新实例
 /// </summary>
 public DefaultDbContext(DbContextOptions options,
                         IEntityConfigurationTypeFinder typeFinder,
                         IEventBus eventBus)
     : base(options, typeFinder, eventBus, null)
 {
 }
Exemplo n.º 21
0
 /// <summary>
 /// 初始化一个<see cref="DbContextBase{TDbContext}"/>类型的新实例
 /// </summary>
 protected DbContextBase(DbContextOptions options, IEntityConfigurationTypeFinder typeFinder)
     : base(options)
 {
     _typeFinder = typeFinder;
 }
Exemplo n.º 22
0
        /// <summary>
        /// 获取指定实体类所属的上下文类型
        /// </summary>
        /// <param name="entityType">实体类型</param>
        /// <returns>上下文类型</returns>
        public Type GetDbContextType(Type entityType)
        {
            IEntityConfigurationTypeFinder typeFinder = _serviceProvider.GetService <IEntityConfigurationTypeFinder>();

            return(typeFinder.GetDbContextTypeForEntity(entityType));
        }
Exemplo n.º 23
0
 public DbContextFactory(IServiceProvider serviceProvider)
 {
     _entityConfigurationTypeFinder = serviceProvider.GetRequiredService <IEntityConfigurationTypeFinder>();
     _serviceProvider = serviceProvider;
 }
Exemplo n.º 24
0
 /// <summary>
 /// 初始化一个<see cref="EntityManager"/>类型的新实例
 /// </summary>
 public EntityManager(IServiceProvider provider)
 {
     _logger     = provider.GetLogger <EntityManager>();
     _typeFinder = provider.GetService <IEntityConfigurationTypeFinder>();
 }