示例#1
0
        protected override ICommandResult ExecuteDeleteCommand(SqlModelCommand <T> dataCommand, IDbCommand command)
        {
            var result = new ModelCommandResult <T>();

            if (TableMapFromDatabase)
            {
                dataCommand.GetTableMap();
            }

            dataCommand.BuildSqlParameters(command);
            dataCommand.BuildSqlCommand();
            command.CommandText = dataCommand.SqlCommandText;

            OnBeforeCommandExecute(this, new ModelCommandBeforeExecuteEventArgs(dataCommand, command, DataCommandType.Delete));

            if (command.CommandText.ToUpper().Contains("WHERE"))
            {
                int records = command.ExecuteNonQuery();
                result.RecordsAffected = records;
                result.AddMessage(string.Format("{0} executed with {1} rows affected", dataCommand.SqlCommandText,
                                                records));
                dataCommand.ResetCommand();
            }
            else
            {
                result.AddError(LogType.Information, "No where in delete " + command.CommandText);
            }
            result.DataCommand = dataCommand;

            return(result);
        }
示例#2
0
 protected override ICommandResult ExecuteTableCreateUpdate(SqlModelCommand <T> dataCommand, IDbCommand command)
 {
     throw new NotImplementedException();
 }
示例#3
0
 protected override Task <ICommandResult> ExecuteInsertCommandAsync(SqlModelCommand <T> dataCommand, IDbCommand command)
 {
     throw new NotImplementedException();
 }
示例#4
0
        protected override ICommandResult ExecuteSelectCommand(SqlModelCommand <T> dataCommand, IDbCommand command)
        {
            if (TableMapFromDatabase)
            {
                var map = dataCommand.GetTableMap();
                if (dataCommand.SelectAll == false)
                {
                    if (!string.IsNullOrEmpty(map))
                    {
                        var columns = dataCommand.GetColumnAttributes();
                        foreach (var columnMap in columns)
                        {
                            bool addColumn = true;
                            if (dataCommand.TableMap == null)
                            {
                                addColumn = false;
                            }

                            var column = dataCommand.TableMap.ColumnMaps.FirstOrDefault(m => m.ColumnName == columnMap.ColumnName);
                            if (column == null)
                            {
                                addColumn = false;
                            }


                            if (addColumn)
                            {
                                dataCommand.Column(columnMap.ColumnName);
                            }
                        }
                        dataCommand.SelectAll = false;
                    }
                }
            }


            dataCommand.BuildSqlCommand();
            dataCommand.BuildSqlParameters(command);
            command.CommandText = dataCommand.SqlCommandText;
            var            items  = new List <T>();
            ICommandResult result = null;

            try
            {
                int rowsIndex = 0;


                OnBeforeCommandExecute(this, new ModelCommandBeforeExecuteEventArgs(dataCommand, command, DataCommandType.Select));
                using (SqlDataReader r = command.ExecuteReader() as SqlDataReader)
                {
                    Type objectType = typeof(T);

                    if (objectType == typeof(DataTable))
                    {
                        result = new DataTableCommandResult();
                        var dt = new DataTable(dataCommand.TableName);
                        dt.Load(r);


                        ((DataTableCommandResult)result).Data = dt;
                        result.RecordsAffected = dt.Rows.Count;

                        foreach (var item in dataCommand.TableMap.ColumnMaps)
                        {
                            if (item.ColumnName != item.PropertyName)
                            {
                                foreach (System.Data.DataColumn column in dt.Columns)
                                {
                                    if (item.ColumnName == column.ColumnName)
                                    {
                                        if (!string.IsNullOrEmpty(item.PropertyName))
                                        {
                                            if (item.IsMapped)
                                            {
                                                column.ColumnName = item.PropertyName;
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        return(result);
                    }
                    result = new ModelCommandResult <T>();

                    var tablename = dataCommand.GetTableAttribute();

                    var accessor = TypeAccessor.Create(objectType);

                    ConstructorInfo ctor = objectType.GetConstructor(Type.EmptyTypes);
                    TrinityActivator.ObjectActivator <T> createdActivator = TrinityActivator.GetActivator <T>(ctor);

                    while (r.Read())
                    {
                        bool userDataManager = false;

                        //https://vagifabilov.wordpress.com/2010/04/02/dont-use-activator-createinstance-or-constructorinfo-invoke-use-compiled-lambda-expressions/

                        var newObject = createdActivator();
                        //var newObject = (T)Activator.CreateInstance(objectType);
                        var dataManager = newObject as IObjectDataManager;


                        if (dataCommand.TableMap != null)
                        {
                            if (dataCommand.TableName != objectType.Name)
                            {
                                if (tablename == dataCommand.TableName)
                                {
                                    if (dataManager != null)
                                    {
                                        userDataManager = true;
                                    }
                                    else
                                    {
                                        userDataManager = false;
                                    }
                                }
                            }
                            else
                            {
                                if (dataManager != null)
                                {
                                    userDataManager = true;
                                }
                            }
                        }

                        if (userDataManager)
                        {
                            dataManager.SetData(r);
                        }
                        else
                        {
                            //TODO Change code to use Reflection.Emit
                            int counter = r.FieldCount;
                            for (int i = 0; i < counter; i++)
                            {
                                var name = r.GetName(i);
                                try
                                {
                                    var fieldType = r.GetFieldType(i);
                                    var value     = r.GetValue(i);
                                    if (dataCommand.TableMap != null)
                                    {
                                        var column =
                                            dataCommand.TableMap.ColumnMaps.FirstOrDefault(m => m.ColumnName == name);

                                        if (column != null)
                                        {
                                            if (!string.IsNullOrEmpty(column.PropertyName))
                                            {
                                                try
                                                {
                                                    if (value != DBNull.Value)
                                                    {
                                                        accessor[newObject, column.PropertyName] = value;
                                                    }
                                                }
                                                catch (Exception e)
                                                {
                                                    try
                                                    {
                                                        if (value != DBNull.Value)
                                                        {
                                                            var prop = objectType.GetProperty(column.PropertyName);
                                                            accessor[newObject, column.PropertyName] = value.ConvertValue(prop);
                                                        }
                                                    }
                                                    catch (Exception exception)
                                                    {
                                                        var prop = objectType.GetProperty(column.PropertyName);
                                                        if (prop != null)
                                                        {
                                                            if (value != DBNull.Value)
                                                            {
                                                                try
                                                                {
                                                                    prop.SetValue(newObject, value, null);
                                                                }
                                                                catch (Exception)
                                                                {
                                                                    prop.SetValue(newObject, value.ConvertValue(prop), null);
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                try
                                                {
                                                    if (value != DBNull.Value)
                                                    {
                                                        accessor[newObject, name] = value;
                                                    }
                                                }
                                                catch (Exception e)
                                                {
                                                    TrySetValue(dataCommand, newObject, objectType, name, value);
                                                }
                                            }
                                        }
                                        else
                                        {
                                            try
                                            {
                                                if (value != DBNull.Value)
                                                {
                                                    accessor[newObject, name] = value;
                                                }
                                            }
                                            catch (Exception e)
                                            {
                                                TrySetValue(dataCommand, newObject, objectType, name, value);
                                            }
                                        }
                                    }
                                    else
                                    {
                                        var prop = objectType.GetProperty(name);
                                        if (prop != null)
                                        {
                                            if (value != DBNull.Value)
                                            {
                                                prop.SetValue(newObject, value, null);
                                            }
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    result.AddError(LogType.Error, string.Format("{1} {0} ", name, dataCommand.TableName), ex);
                                }
                            }
                        }
                        items.Add(newObject);
                        rowsIndex++;
                    }
                }
                result.RecordsAffected = rowsIndex;
            }
            catch (Exception exception)
            {
                result.AddError(LogType.Error, $"{dataCommand.TableName} {dataCommand.SqlCommandText} {typeof(T).FullName}", exception);
            }
            ((ModelCommandResult <T>)result).Data = items;
            result.AddMessage(string.Format("{0} executed with {1} rows affected", dataCommand.SqlCommandText, result.RecordsAffected));
            //TODO change class to use base type


            dataCommand.OnCommandExecuted(new ModelCommandExecutedEventArgs <T> {
                Result = (ModelCommandResult <T>)result
            });

            dataCommand.ResetCommand();
            result.DataCommand = dataCommand;
            return(result);
        }
示例#5
0
        protected override async Task <ICommandResult> ExecuteSelectCommandAsync(SqlModelCommand <T> dataCommand,
                                                                                 IDbCommand command)
        {
            if (TableMapFromDatabase)
            {
                dataCommand.GetTableMap();
            }

            dataCommand.BuildSqlCommand();
            dataCommand.BuildSqlParameters(command);
            command.CommandText = dataCommand.SqlCommandText;
            var            items  = new List <T>();
            ICommandResult result = null;

            try
            {
                int rowsIndex  = 0;
                var sqlCommand = command as SqlCommand;

                OnBeforeCommandExecute(this, new ModelCommandBeforeExecuteEventArgs(dataCommand, command, DataCommandType.Select));

                using (SqlDataReader r = await sqlCommand.ExecuteReaderAsync())
                {
                    Type objectType = typeof(T);

                    if (objectType == typeof(DataTable))
                    {
                        result = new DataTableCommandResult();
                        var dt = new DataTable(dataCommand.TableName);
                        dt.Load(r);
                        ((DataTableCommandResult)result).Data = dt;
                        result.RecordsAffected = dt.Rows.Count;

                        return(result);
                    }
                    result = new ModelCommandResult <T>();

                    var tablename = dataCommand.GetTableAttribute();
                    while (await r.ReadAsync())
                    {
                        bool userDataManager = false;
                        var  newObject       = (T)Activator.CreateInstance(objectType);
                        var  dataManager     = newObject as IObjectDataManager;

                        if (dataManager != null)
                        {
                            userDataManager = true;
                        }

                        if (dataCommand.TableMap != null)
                        {
                            if (dataCommand.TableName != objectType.Name)
                            {
                                if (tablename == dataCommand.TableName)
                                {
                                    if (dataManager != null)
                                    {
                                        userDataManager = true;
                                    }
                                    else
                                    {
                                        userDataManager = false;
                                    }
                                }
                            }
                        }

                        if (userDataManager)
                        {
                            dataManager.SetData(r);
                        }
                        else
                        {
                            //TODO Change code to use Reflection.Emit
                            int counter = r.FieldCount;
                            for (int i = 0; i < counter; i++)
                            {
                                var name = r.GetName(i);
                                try
                                {
                                    var fieldType = r.GetFieldType(i);
                                    var value     = r.GetValue(i);
                                    if (dataCommand.TableMap != null)
                                    {
                                        var column =
                                            dataCommand.TableMap.ColumnMaps.FirstOrDefault(m => m.ColumnName == name);

                                        if (column != null)
                                        {
                                            if (!string.IsNullOrEmpty(column.PropertyName))
                                            {
                                                var prop = objectType.GetProperty(column.PropertyName);
                                                if (prop != null)
                                                {
                                                    if (value != DBNull.Value)
                                                    {
                                                        prop.SetValue(newObject, value, null);
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                TrySetValue(dataCommand, newObject, objectType, name, value);
                                            }
                                        }
                                        else
                                        {
                                            TrySetValue(dataCommand, newObject, objectType, name, value);
                                        }
                                    }
                                    else
                                    {
                                        var prop = objectType.GetProperty(name);
                                        if (prop != null)
                                        {
                                            if (value != DBNull.Value)
                                            {
                                                prop.SetValue(newObject, value, null);
                                            }
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    result.AddError(LogType.Error,
                                                    string.Format("{1} {0} ", name, dataCommand.TableName), ex);
                                }
                            }
                        }
                        items.Add(newObject);
                        rowsIndex++;
                    }
                }
                result.RecordsAffected = rowsIndex;
            }
            catch (Exception exception)
            {
                result.AddError(LogType.Error, dataCommand.TableName + " " + typeof(T).FullName, exception);
            }

            ((ModelCommandResult <T>)result).Data = items;
            result.AddMessage(string.Format("{0} executed with {1} rows affected", dataCommand.SqlCommandText,
                                            result.RecordsAffected));
            //TODO change class to use base type
            dataCommand.OnCommandExecuted(new ModelCommandExecutedEventArgs <T> {
                Result = (ModelCommandResult <T>)result
            });
            dataCommand.ResetCommand();
            result.DataCommand = dataCommand;
            return(result);
        }
示例#6
0
        protected override ICommandResult ExecuteInsertCommand(SqlModelCommand <T> dataCommand, IDbCommand command)
        {
            var result = new ModelCommandResult <T>();
            var item   = dataCommand.Model as IModelBase;

            if (item != null)
            {
                if (item.Errors != null)
                {
                    if (item.HasErrors())
                    {
                        result.AddError(LogType.Error, "Model has validation error");
                        return(result);
                    }
                }
            }
            if (TableMapFromDatabase)
            {
                dataCommand.GetTableMap();
            }


            var  select      = string.Empty;
            bool identity    = false;
            var  retunColums = new Dictionary <string, string>();

            dataCommand.AddChanges();
            foreach (var key in dataCommand.PrimaryKeys)
            {
                var column = dataCommand.TableMap.ColumnMaps.FirstOrDefault(m => m.PropertyName == key);

                if (column == null)
                {
                    column = dataCommand.TableMap.ColumnMaps.FirstOrDefault(m => m.ColumnName == key);
                }

                if (column != null)
                {
                    if (column.IsIdentity)
                    {
                        select  += string.Format(" {0},", column.ColumnName);
                        identity = true;
                        retunColums.Add(column.ColumnName, column.PropertyName);
                        if (dataCommand.Changes.Contains(column.PropertyName))
                        {
                            dataCommand.Changes.Remove(column.PropertyName);
                        }
                    }
                }
            }

            var guidIdColumns =
                dataCommand.TableMap.ColumnMaps.Where(map => !string.IsNullOrEmpty(map.Default))
                .Where(
                    map =>
                    map.Default.ToUpper().Contains("NEWSEQUENTIALID") ||
                    map.Default.ToUpper().ToUpper().Contains("NEWID"))
                .ToList();

            foreach (var guidIdColumn in guidIdColumns)
            {
                select += string.Format(" {0},", guidIdColumn.ColumnName);
                retunColums.Add(guidIdColumn.ColumnName, guidIdColumn.PropertyName);
            }

            if (identity)
            {
                dataCommand.SetWhereText(string.Format(
                                             " SELECT SCOPE_IDENTITY() as [{0}]", retunColums.FirstOrDefault().Key
                                             ));
            }


            foreach (var change in dataCommand.Changes)
            {
                var column = dataCommand.TableMap.ColumnMaps.FirstOrDefault(m => m.PropertyName == change);
                if (column != null)
                {
                    dataCommand.Value(column.ColumnName, dataCommand.GetValue(change));
                }
            }

            dataCommand.BuildSqlParameters(command);
            dataCommand.BuildSqlCommand();
            command.CommandText = dataCommand.SqlCommandText;

            OnBeforeCommandExecute(this, new ModelCommandBeforeExecuteEventArgs(dataCommand, command, DataCommandType.Insert));


            using (var dataReader = command.ExecuteReader())
            {
                result.RecordsAffected = dataReader.RecordsAffected;
                if (dataReader.RecordsAffected == 0)
                {
                    result.AddError(LogType.Information, "No rows affected");
                }
                else
                {
                    dataCommand.SetWhereText(string.Empty);
                    dataCommand.CommandType = DataCommandType.Update;
                }
                while (dataReader.Read())
                {
                    for (int i = 0; i < 1; ++i)
                    {
                        var name     = dataReader.GetName(i);
                        var property = retunColums[name];
                        dataCommand.SetValue(property, dataReader.GetValue(i).ToInt());
                    }
                }
            }
            //TODO error when transaction is full
            result.AddMessage(string.Format("{0} executed with {1} rows affected", dataCommand.SqlCommandText,
                                            result.RecordsAffected));
            dataCommand.ResetCommand();
            result.DataCommand = dataCommand;
            return(result);
        }
示例#7
0
        protected override ICommandResult ExecuteUpdateCommand(SqlModelCommand <T> dataCommand, IDbCommand command)
        {
            var result = new ModelCommandResult <T>();
            var item   = dataCommand.Model as IModelBase;

            //TODO beforeExectute
            if (item != null)
            {
                if (item.Error == null)
                {
                    if (item.HasErrors())
                    {
                        result.AddError(LogType.Error, "Model has validation error");
                        return(result);
                    }
                }
            }
            if (TableMapFromDatabase)
            {
                dataCommand.GetTableMap();
            }


            if (dataCommand.TableMap.TableType == "VIEW")
            {
                if (item.Configuration == null)
                {
                    result.AddMessage(string.Format("The command is type of View and has no merge configuration"));
                    return(result);
                }
            }
            else
            {
                if (dataCommand.Track == false)
                {
                    dataCommand.AddChanges();
                }
                dataCommand.BuildKeys();
                foreach (var change in dataCommand.Changes)
                {
                    if (dataCommand.TableMap != null)
                    {
                        var column = dataCommand.TableMap.ColumnMaps.FirstOrDefault(m => m.PropertyName == change);

                        if (column == null)
                        {
                            column = dataCommand.TableMap.ColumnMaps.FirstOrDefault(m => m.ColumnName == change);
                        }

                        if (column?.IsIdentity == false)
                        {
                            dataCommand.Value(column.ColumnName, dataCommand.GetValue(change));
                        }
                    }
                    else
                    {
                        dataCommand.Value(change, dataCommand.GetValue(change));
                    }
                }

                OnBeforeCommandExecute(this, new ModelCommandBeforeExecuteEventArgs(dataCommand, command, DataCommandType.Update));

                if (dataCommand.Columns.Count > 0 && dataCommand.Changes.Count > 0)
                {
                    dataCommand.BuildSqlParameters(command);
                    dataCommand.BuildSqlCommand();
                    command.CommandText = dataCommand.SqlCommandText;



                    if (command.CommandText.Contains("WHERE"))
                    {
                        int resultIndex = command.ExecuteNonQuery();
                        result.RecordsAffected = resultIndex;
                        if (resultIndex == 0)
                        {
                            result.AddError(LogType.Information, "No rows affected");
                        }
                        else
                        {
                            dataCommand.ResetCommand();
                        }
                    }
                    else
                    {
                        result.AddError(LogType.Information, "No where in update");
                    }
                    result.AddMessage(string.Format("{0} executed with {1} rows affected", command.CommandText,
                                                    result.RecordsAffected));
                }
                result.DataCommand = dataCommand;
            }
            return(result);
        }