예제 #1
0
        static void Main(string[] args)
        {
            try
            {
                var options = new CmdOptions();
                CommandLine.Parser.Default.ParseArguments(args, options);
                IDbMapper mapper = null;
                switch (options.DataProvider)
                {
                case "System.Data.SqlClient":
                    mapper = new DBMapperMSSql(options.ConStr);
                    break;

                case "MySql.Data.MySqlClient":
                    mapper = new DbMapperMySql(options.ConStr);
                    break;

                case "System.Data.SQLite":
                    mapper = new DbMapperSqlite(options.ConStr);
                    break;

                default:
                    break;
                }

                string targetFile = Path.Combine(options.TargetFolder, "DbContent.cs");
                mapper.MapDataBase(targetFile, options.Namespace);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
예제 #2
0
 public DbQuery(IDbProvider dbProvider, IDbMapper <TModel> dbMapper)
 {
     _dbProvider = dbProvider;
     _dbMapper   = dbMapper;
     _tableName  = typeof(TModel).GetTypeInfo().Name.BuildTableName();
     _parameters = new Dictionary <string, object>();
 }
예제 #3
0
 public DbQuery(IDbProvider dbProvider, IDbMapper <TModel> dbMapper)
 {
     DbMapper   = dbMapper;
     TableName  = typeof(TModel).BuildTableName();
     DbProvider = dbProvider;
     Parameters = new Dictionary <string, object>();
 }
예제 #4
0
 public EntityJoiner(int timeout, IDb db, IDbScripter scripter, IDbMapper mapper, IEnumerable <P> instances)
 {
     _timeout    = timeout;
     m_Db        = db;
     m_Scripter  = scripter;
     m_Mapper    = mapper;
     m_Instances = instances;
 }
예제 #5
0
        /// <summary>
        /// 实现对象的自动插入操作.
        /// </summary>
        /// <typeparam name="T">对象类型.</typeparam>
        /// <typeparam name="Mapper">数据库Mapper对象类型.</typeparam>
        /// <param name="entity">对象实例.</param>
        /// <param name="mapperObject">数据库Mapper对象,如SqlServer,Sqlite.</param>
        /// <param name="containsIdentityColumn">是否包含自动插入操作列.</param>
        public static void Insert <T, Mapper>(this T entity, Mapper mapperObject, bool containsIdentityColumn = false)
            where T : class, new()
            where Mapper : IMapperBase
        {
            IDbMapper <T> mapper = mapperObject as IDbMapper <T>;

            mapper.Insert(entity, containsIdentityColumn);
        }
예제 #6
0
        private IDbMapper GetMapper()
        {
            if (this.dbMapper == null)
            {
                Initialize();
                this.dbMapper = new DbMapper(this.masterConn);
            }

            return(this.dbMapper);
        }
예제 #7
0
        // Called if its a ManyToMany join, we can grab the join conditions from out attributes, no need for expression
        public DbQuery(IDbProvider dbProvider, JoinType joinType, IDbMapper <TModel> dbMapper) : base(dbProvider, dbMapper)
        {
            const string joinFormat = "[{0}].[Id] == [{1}].[{2}Id]";

            _joinType      = joinType;
            _joinTableName = typeof(TJoinTo).BuildTableName();
            var joinExpression = string.Format(joinFormat, TableName, _joinTableName, TableName.Singularize());

            _joinExpression = BuildJoinExpression(joinType, joinExpression);
        }
예제 #8
0
        /// <summary>
        ///     Update the record if it doesn't exist, otherwise create a new one.
        /// </summary>
        /// <typeparam name="TModel">Model type</typeparam>
        /// <param name="model">Model Object to create or update</param>
        /// <param name="dbMapper">Used to map the data in the model object to parameters to be used in database calls</param>
        public async Task CreateOrUpdate <TModel>(TModel model,
                                                  IDbMapper <TModel> dbMapper)
            where TModel : class, new()
        {
            using (var transaction = GetNewTransaction())
            {
                await transaction.Initialize(false);

                await transaction.CreateOrUpdate(model, dbMapper);
            }
        }
예제 #9
0
        /// <summary>
        ///     Create a new record based on a Model
        /// </summary>
        /// <typeparam name="TModel">Model Type</typeparam>
        /// <param name="model">Model Object</param>
        /// <param name="dbMapper"></param>
        /// <returns>The uniqueidentifier (Guid) of the newly created record.</returns>
        public void Create <TModel>(TModel model, IDbMapper <TModel> dbMapper) where TModel : class, new()
        {
            var tableName     = typeof(TModel).GetTypeInfo().Name.BuildTableName();
            var fieldNameList = dbMapper.FieldNames;
            var commandParams = dbMapper.BuildDbParametersFrom(model);

            var parameters  = "@" + string.Join(",@", fieldNameList);
            var fields      = string.Join(",", fieldNameList);
            var commandText = string.Format(Dialect.InsertInto, tableName, fields, parameters);

            Commands.Add(new TransactionCommand(commandText, commandParams));
            UpdateManyToManyRelationsAsync(model, tableName, dbMapper);
        }
예제 #10
0
        public override async Task CreateOrUpdateAsync <TModel>(TModel model, IDbMapper <TModel> dbMapper)
        {
            var tableName     = typeof(TModel).GetTypeInfo().Name.BuildTableName();
            var fieldNameList = dbMapper.FieldNames;
            var commandParams = dbMapper.BuildDbParametersFrom(model);

            var parameters  = "@" + string.Join(",@", fieldNameList);
            var fields      = string.Join(",", fieldNameList);
            var commandText = string.Format(Dialect.CreateOrUpdate, tableName, fields, parameters);

            await ExecuteNonQueryAsync(commandText, commandParams).ConfigureAwait(false);
            await UpdateManyToManyRelationsAsync(model, tableName, dbMapper).ConfigureAwait(false);
        }
예제 #11
0
        public async Task Create <TModel>(TModel model, IDbMapper <TModel> dbMapper) where TModel : class, new()
        {
            var tableName     = typeof(TModel).BuildTableName();
            var fieldNameList = dbMapper.FieldNames;
            var commandParams = dbMapper.BuildDbParametersFrom(model);

            var parameters  = "@" + string.Join(",@", fieldNameList);
            var fields      = string.Join(",", fieldNameList);
            var commandText = string.Format(Dialect.InsertInto, tableName, fields, parameters);

            await ExecuteNonQuery(commandText, commandParams).ConfigureAwait(false);

            await UpdateManyToManyRelationsAsync(model, tableName, dbMapper).ConfigureAwait(false);
        }
예제 #12
0
        public IQueryGenerator <T> QueryGenerator <T>(IDbMapper <T> mapper)
        {
            if (_adoDbFactory.DatabaseType == DatabaseType.SqlServer)
            {
                return(new SqlServerQueryGenerator <T>(mapper));
            }

            if (_adoDbFactory.DatabaseType == DatabaseType.Oracle)
            {
                return(new OracleQueryGenerator <T>(mapper));
            }

            return(new GeneralQueryGenerator <T>(mapper));
        }
예제 #13
0
        /// <summary>
        ///     UpdateAsync the Database Record of a specified model.
        /// </summary>
        /// <typeparam name="TModel">Model type</typeparam>
        /// <param name="model">Model Object to update</param>
        /// <param name="dbMapper">Used to map the data in the model object to parameters to be used in database calls</param>
        public void Update <TModel>(TModel model, IDbMapper <TModel> dbMapper) where TModel : class, new()
        {
            var modelType      = typeof(TModel);
            var identifierName = modelType.GetPrimaryKeyName();

            var tableName     = typeof(TModel).GetTypeInfo().Name.BuildTableName();
            var fieldNameList = dbMapper.FieldNames;
            var commandParams = dbMapper.BuildDbParametersFrom(model);

            var setFieldText = fieldNameList.Select(field => string.Format("[{0}] = @{0}", field)).ToList();
            var whereClause  = string.Format(Dialect.Where, string.Format("{0} = @{0}", identifierName));
            var commandText  = string.Format(Dialect.Update, tableName, string.Join(",", setFieldText),
                                             whereClause);

            Commands.Add(new TransactionCommand(commandText, commandParams));
            UpdateManyToManyRelationsAsync(model, tableName, dbMapper);
        }
예제 #14
0
        public async Task Update <TModel>(TModel model, IDbMapper <TModel> dbMapper) where TModel : class, new()
        {
            var modelType      = typeof(TModel);
            var identifierName = modelType.GetPrimaryKeyName();

            var tableName     = typeof(TModel).BuildTableName();
            var fieldNameList = dbMapper.FieldNames;
            var commandParams = dbMapper.BuildDbParametersFrom(model);

            var setFieldText = fieldNameList.Select(field => string.Format("[{0}] = @{0}", field)).ToList();
            var whereClause  = string.Format(Dialect.Where, string.Format("{0} = @{0}", identifierName));
            var commandText  = string.Format(Dialect.Update, tableName, string.Join(",", setFieldText),
                                             whereClause);

            await ExecuteNonQuery(commandText, commandParams).ConfigureAwait(false);
            await UpdateManyToManyRelationsAsync(model, tableName, dbMapper).ConfigureAwait(false);
        }
예제 #15
0
        public BaseService()
        {
            Provider = Provider.MsSql; //for test methods

            switch (Provider)
            {
                case Provider.MsSql:
                    DbMapper = new MsSqlServerMapper("DefaultConnection", new DefaultValueMapper());
                    break;
                case Provider.Postgres:
                    DbMapper = new PostgresMapper("Postgres", new DefaultValueMapper());
                    break;
                default:
                    throw new NotImplementedException();
            }

            CrudService = new CrudService(DbMapper);
            BaselineService = new BaselineService(DbMapper);
        }
        public override void CreateOrUpdate <TModel>(TModel model, IDbMapper <TModel> dbMapper)
        {
            var modelType     = typeof(TModel);
            var tableName     = typeof(TModel).GetTypeInfo().Name.BuildTableName();
            var fieldNameList = dbMapper.FieldNames;
            var commandParams = dbMapper.BuildDbParametersFrom(model);

            var insertParams = "@" + string.Join(",@", fieldNameList);
            var insertFields = string.Join(",", fieldNameList);
            var updateFields = string.Join(",", fieldNameList.Select(field => string.Format("[{0}] = @{0}", field)).ToList());
            var whereClause  = string.Format(Dialect.Where, string.Format("{0} = @{0}", modelType.GetPrimaryKeyName()));

            var commandText = string.Format(Dialect.CreateOrUpdate,
                                            tableName,
                                            updateFields,
                                            whereClause,
                                            insertFields,
                                            insertParams);

            Commands.Add(new TransactionCommand(commandText, commandParams));
            UpdateManyToManyRelationsAsync(model, tableName, dbMapper);
        }
예제 #17
0
        public override async Task CreateOrUpdateAsync <TModel>(TModel model, IDbMapper <TModel> dbMapper)
        {
            var modelType     = typeof(TModel);
            var tableName     = typeof(TModel).GetTypeInfo().Name.BuildTableName();
            var fieldNameList = dbMapper.FieldNames;
            var commandParams = dbMapper.BuildDbParametersFrom(model);

            var insertParams = "@" + string.Join(",@", fieldNameList);
            var insertFields = string.Join(",", fieldNameList);
            var updateFields = string.Join(",", fieldNameList.Select(field => string.Format("[{0}] = @{0}", field)).ToList());
            var whereClause  = string.Format(Dialect.Where, string.Format("{0} = @{0}", GetPrimaryKeyName(modelType)));

            var commandText = string.Format(Dialect.CreateOrUpdate,
                                            tableName,
                                            updateFields,
                                            whereClause,
                                            insertFields,
                                            insertParams);

            await ExecuteNonQueryAsync(commandText, commandParams).ConfigureAwait(false);
            await UpdateManyToManyRelationsAsync(model, tableName, dbMapper).ConfigureAwait(false);
        }
예제 #18
0
 /// <summary>
 /// Construct a new DbLayer
 /// </summary>
 /// <param name="dbInterface">An interface to an underlying database</param>
 /// <param name="descriptor">Metadata to enable mapping T's to database tables</param>
 /// <param name="mapper">An object-relational mapper</param>
 protected DbLayer(IDbInterface <TDbParameter> dbInterface, IDbObjectDescriptor descriptor, IDbMapper <T> mapper)
 {
     DbInterface = dbInterface ?? throw new ArgumentNullException(nameof(dbInterface));
     Descriptor  = descriptor ?? throw new ArgumentNullException(nameof(descriptor));
     Mapper      = mapper ?? throw new ArgumentNullException(nameof(mapper));
 }
예제 #19
0
        /// <summary>
        ///     Updates all Join Tables based on the <see cref="ManyToManyAttribute" />
        /// </summary>
        /// <typeparam name="TModel">Object model Type</typeparam>
        /// <param name="model">Actual object model</param>
        /// <param name="tableName">The name of the table</param>
        /// <param name="dbMapper">Used to map the data in the model object to parameters to be used in database calls</param>
        protected async Task UpdateManyToManyRelationsAsync <TModel>(TModel model,
                                                                     string tableName, IDbMapper <TModel> dbMapper) where TModel : class, new()
        {
            var primaryKey = model.GetType().GetPrimaryKeyName();
            var leftModel  = dbMapper.BuildDbParametersFrom(model).FirstOrDefault(k => k.Key == primaryKey);
            var leftKey    = typeof(TModel).Name.Replace("Model", string.Empty) + primaryKey;
            var parameters = new Dictionary <string, object> {
                { "@" + leftKey, leftModel.Value }
            };
            var manyToManyFields =
                typeof(TModel).GetRuntimeProperties()
                .Where(property => property.GetCustomAttributes(true).Any(a => a.GetType().Name == nameof(ManyToManyAttribute)));

            foreach (var collection in manyToManyFields)
            {
                //                if (!IsGenericList(collection))
                //                {
                //                    throw new ArgumentException("The property must be an ICollection<>");
                //                }

                var joinTableName     = GetJoinTableName(tableName, collection.Name);
                var deleteWhereClause = string.Format(Dialect.Where, string.Format("{0} = @{0}", leftKey));
                var deleteCommandText = string.Format(Dialect.DeleteFrom, joinTableName, deleteWhereClause);
                // Delete ALL records in the Join table associated with the `leftModel`
                await ExecuteNonQuery(deleteCommandText, parameters).ConfigureAwait(false);

                var manyToManyCollection = collection.PropertyType.GenericTypeArguments.FirstOrDefault();
                var listValues           = (IEnumerable <object>)collection.GetValue(model, null);
                if (listValues == null)
                {
                    continue;
                }

                foreach (var value in listValues.Distinct())
                {
                    if (manyToManyCollection == null)
                    {
                        throw new ArgumentException();
                    }
                    var rightProperties          = manyToManyCollection.GetRuntimeProperties();
                    var manyToManyCollectionName = manyToManyCollection.Name.Replace("Model", string.Empty);
                    foreach (var rightProperty in rightProperties)
                    {
                        var rightPropertyName = rightProperty.Name;
                        if (rightPropertyName != primaryKey)
                        {
                            continue; // short circuit the loop if we're not dealing with the primary key.
                        }
                        var rightKey   = manyToManyCollectionName + rightPropertyName;
                        var rightValue = rightProperty.GetValue(value, null);
                        parameters.Add("@" + rightKey, rightValue);
                        var fieldsToInsert = string.Format(Dialect.JoinFields, leftKey, rightKey);
                        // "[{0}], [{1}]"
                        var parametersToSet = string.Format(Dialect.JoinParameters, leftKey, rightKey);
                        // "@{0}, @{1}"
                        var insertCommandText = string.Format(Dialect.InsertInto, joinTableName,
                                                              fieldsToInsert,
                                                              parametersToSet);
                        await ExecuteNonQuery(insertCommandText, parameters).ConfigureAwait(false);

                        // Remove the parameter for the next iteration.
                        parameters.Remove("@" + rightKey);
                    }
                }
            }
        }
예제 #20
0
 public GeneralQueryFormatter(IDbMapper <T> mapper)
 {
     Mapper = mapper;
 }
예제 #21
0
 public abstract Task CreateOrUpdate <TModel>(TModel model, IDbMapper <TModel> dbMapper) where TModel : class, new();
예제 #22
0
 /// <summary>
 /// Construct a new SqlDbLayer
 /// </summary>
 /// <param name="connectionString">The db's connection string</param>
 /// <param name="descriptor">Metadata to enable mapping T's to database tables</param>
 /// <param name="mapper">An object-relational mapper</param>
 protected SqlLayer(string connectionString, SqlObjectDescriptor <T> descriptor, IDbMapper <T> mapper) :
     base(new SqlInterface(connectionString), descriptor, mapper)
 {
 }
예제 #23
0
 /// <summary>
 /// Construct a new PostgresMappedLayer
 /// </summary>
 /// <param name="connectionString">The db's connection string</param>
 /// <param name="descriptor">Metadata to enable mapping T's to database tables</param>
 /// <param name="mapper">An object-relational mapper</param>
 public PostgresMappedLayer(string connectionString, PostgresMappedObjectDescriptor <T> descriptor,
                            IDbMapper <T> mapper) :
     base(new PostgresInterface(connectionString), descriptor, mapper)
 {
 }
예제 #24
0
 public MsSqlAccessor(IMsSqlScripter scripter, IDbMapper mapper, IDb db, IDbAggregator aggregator)
     : base(scripter, mapper, db, aggregator)
 {
     m_Scripter = scripter;
     m_Db       = db;
 }
예제 #25
0
 public DbAsyncAccessor(IDbScripter scripter, IDbMapper mapper, IDb db)
     : base(scripter, mapper, db)
 {
 }
예제 #26
0
 public AccessorSetup(IDbScripter scripter, IDbMapper mapper, IDbAggregator aggregator)
 {
     _scripter   = scripter;
     _mapper     = mapper;
     _aggregator = aggregator;
 }
예제 #27
0
 public GeneralQueryGenerator(IDbMapper <T> mapper)
 {
     Formatter = new GeneralQueryFormatter <T>(mapper);
 }
예제 #28
0
 public TableDal(IFileHelper file, Settings.Settings setting, IDbMapper dbMapper)
 {
     _fileHelper = file;
     _setting    = setting;
     _dbMapper   = dbMapper;
 }
예제 #29
0
 public MsSqlAccessor(IMsSqlScripter scripter, IDbMapper mapper, IDb db)
     : base(scripter, mapper, db)
 {
     m_Scripter = scripter;
     m_Db       = db;
 }
예제 #30
0
 public BaselineService(IDbMapper dbMapper)
     : base(dbMapper)
 {
 }
예제 #31
0
 public MsSqlAsyncAccessor(IMsSqlScripter scripter, IDbMapper mapper, IDb db, IDbAggregator aggregator)
     : base(scripter, mapper, db, aggregator)
 {
     _sqlAccessor = new MsSqlAccessor(scripter, mapper, db, aggregator);
 }
예제 #32
0
 /// <summary>
 ///     Create a new record based on a Model
 /// </summary>
 /// <typeparam name="TModel">Model Type</typeparam>
 /// <param name="model">Model Object</param>
 /// <param name="dbMapper"></param>
 /// <returns>The uniqueidentifier (Guid) of the newly created record.</returns>
 public void Create <TModel>(TModel model, IDbMapper <TModel> dbMapper) where TModel : class, new()
 {
     CreateAsync(model, dbMapper).Wait();
 }