Example #1
0
        private IDbSet CreateDbSet(Type type, TableAttribute table, IColumnInfoCollection columns)
        {
            if (!_iDbSet.IsAssignableFrom(type))
            {
                type = GetDbSetType(type);
            }
            var ctor     = type.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { typeof(TableAttribute), typeof(IColumnInfoCollection), typeof(DbContext) }, null);
            var instance = (IDbSet)ctor.Invoke(new object[] { table, columns, _dbContext });

            instance.Init();
            return(instance);
        }
        private Point CalculateCellOffset(ColumnBase column, IColumnInfoCollection <double> columnsOffset)
        {
            if (column == null)
            {
                return(new Point());
            }

            Debug.Assert(columnsOffset != null);
            Debug.Assert(columnsOffset.Contains(column));

            var columnOffset = columnsOffset[column];

            return(new Point(columnOffset, 0d));
        }
Example #3
0
        private void UpdateMigrationHistoryIfNecessary(IDbSet dbSet, IColumnInfoCollection columns)
        {
            _dbSets.Add(dbSet);
            var table         = dbSet.Table;
            var storedColumns = _migrationHistory.Where(e => e.TableName == table.Name && e.TableSchema == table.Schema).ToList();

            if (!columns.SequenceEqual(storedColumns))
            {
                dbSet.UpdateTable(storedColumns);
                //TODO: this is an immediate delete!
                _migrationHistory.Delete(e => e.TableName == table.Name && e.TableSchema == table.Schema);
                foreach (var column in dbSet.Columns)
                {
                    _migrationHistory.Add(column);
                }
            }
        }
        private Point CalculateCellOffset(ColumnBase column, IColumnInfoCollection <double> columnsOffset, double horizontalOffset, double fixedColumnsWidth, double compensationOffset)
        {
            if (column == null)
            {
                return(new Point());
            }

            Debug.Assert(columnsOffset != null);
            Debug.Assert(columnsOffset.Contains(column));

            var columnOffset = columnsOffset[column];

            // Calculate the offset of the cell's parent column:
            //    The original offset of the Column
            //    - the horizontal offset of the ScrollViewer to scroll to the right
            //    - the width of the fixed columns since we are in the Scrolling FixedCellSubPanel
            //    + the compensation offset used in master detail to avoid scrolling when not required
            return(new Point(columnOffset - horizontalOffset - fixedColumnsWidth + compensationOffset, 0d));
        }
Example #5
0
 public override void BulkInsert(IEnumerable entities, TableAttribute table, IColumnInfoCollection columns)
 {
     using (_connection = OpenConnection())
     {
         lock (_connection)
         {
             _transaction = null;
             var sb = new StringBuilder();
             foreach (var entity in entities)
             {
                 var expression = CreateInsertExpression(entity, table, columns);
                 var visitor    = new SqlCommandTextVisitor(this);
                 visitor.Visit(expression);
                 sb.AppendLine(visitor.CommandText);
             }
             ExecuteNonQuery(sb.ToString());
         }
     }
 }
Example #6
0
        protected object MapType(Type type, Dictionary <string, object> values, IColumnInfoCollection columns)
        {
            var entityType = type;
            var first      = values.First();

            if (columns == null)
            {
                if (values.Count == 1)
                {
                    return(ColumnMapper.MapToType(first.Value));
                }
                else
                {
                    throw new NotSupportedException();
                }
            }

            var skip = 0;

            if (first.Key == ColumnMapper.DiscriminatorColumnName)
            {
                entityType = ColumnMapper.MapType(first.Value);
                skip       = 1;
            }

            var proxyType = DynamicProxy.Instance.GetProxyType(entityType);
            var instance  = (IEntityProxy)Activator.CreateInstance(proxyType);

            foreach (var kvp in values.Skip(skip))
            {
                var name  = kvp.Key;
                var value = kvp.Value;

                columns.SetValue(instance, name, value, ColumnMapper);
            }
            instance.ClearDirty();
            return(instance);
        }
        public void SetValue(IEntityProxy instance, string columnName, object value, ColumnMapper mapper)
        {
            //TODO: get rid of reflection

            var parts = columnName.Split('.');
            var obj   = instance;
            IColumnInfoCollection columns = this;
            var type = GetObjectType(obj);

            if (typeof(IEntityProxy).IsAssignableFrom(type))
            {
                type = type.BaseType;
            }
            for (var i = 0; i < parts.Length; i++)
            {
                var part         = parts[i];
                var propertyName = columns[part].PropertyName;
                var pi           = type.GetProperty(propertyName);
                if (pi == null || !pi.CanWrite)
                {
                    continue;
                }
                if (i == parts.Length - 1)
                {
                    var mappedValue = mapper.MapToType(value, pi);
                    pi.SetValue(obj, mappedValue);
                    obj.State = EntityState.Unchanged;
                }
                else
                {
                    columns = columns[part].ReferenceTable;
                    obj     = pi.GetValue(obj) as IEntityProxy;
                    type    = GetObjectType(obj);
                }
            }
        }
Example #8
0
        public IColumnInfoCollection Map(Type baseType, TableAttribute table = null)
        {
            if (ContainsKey(baseType))
            {
                return(this[baseType]);
            }

            var collection = (IColumnInfoCollection)typeof(ColumnInfoCollection <>).MakeGenericType(baseType)
                             .GetConstructors()
                             .First()
                             .Invoke(new object[] { table, null });
            var columns = new Dictionary <string, ColumnInfo>();

            if (collection.MappedTypes.Length > 1)
            {
                columns.Add(DiscriminatorColumnName, new ColumnInfo
                {
                    TableName             = table != null ? table.Name : null,
                    TableSchema           = table != null ? table.Schema : null,
                    ColumnName            = DiscriminatorColumnName,
                    ColumnType            = "nvarchar(255)",
                    IsDiscriminatorColumn = true,
                    IndexType             = IndexType.Default
                });
            }

            foreach (var pi in collection.MappedTypes.SelectMany(t => t.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)))
            {
                if (IsIgnorable(pi))
                {
                    continue;
                }
                var columnTypeAttribute          = GetColumnType(pi);
                var crossTableReferenceAttribute = columnTypeAttribute as CrossTableReferenceAttribute;
                if (crossTableReferenceAttribute != null)
                {
                    collection.CrossReferences.Add(new CrossReference(crossTableReferenceAttribute.EntityType));
                    continue;
                }
                var foreignKeyAttribute = columnTypeAttribute as ForeignKeyAttribute;
                IColumnInfoCollection referenceTable = null;
                if (foreignKeyAttribute != null)
                {
                    referenceTable = foreignKeyAttribute.DbSet.Columns;
                }

                var columnType = columnTypeAttribute.ToString();
                var columnName = pi.Name;
                if (columns.ContainsKey(columnName))
                {
                    if (columns[columnName].ColumnType != columnType)
                    {
                        columnName = pi.DeclaringType.Name + pi.Name;
                    }
                    else
                    {
                        columns[columnName].DeclaringTypes.Add(pi.DeclaringType);
                        continue;
                    }
                }

                var    isNullable   = IsNullable(pi);
                object defaultValue = null;
                try
                {
                    defaultValue = isNullable ? null : Activator.CreateInstance(pi.PropertyType);
                }
                catch { }

                var indexAttribute = pi.GetAttribute <IndexAttribute>();

                columns.Add(columnName, new ColumnInfo
                {
                    TableName      = table != null ? table.Name : null,
                    TableSchema    = table != null ? table.Schema : null,
                    ColumnName     = columnName,
                    ColumnType     = columnType,
                    DeclaringTypes = new List <Type> {
                        pi.DeclaringType
                    },
                    PropertyName   = pi.Name,
                    IsNullable     = isNullable,
                    IsIdentity     = pi.HasAttribute <KeyAttribute>(),
                    DefaultValue   = defaultValue,
                    IndexType      = indexAttribute != null ? indexAttribute.Type : (IndexType?)null,
                    ReferenceTable = referenceTable
                });
            }

            collection.SetCollection(columns.Values);
            _typeCache[baseType] = collection;
            return(collection);
        }
Example #9
0
 internal DbSet(TableAttribute table, IColumnInfoCollection columns, DbContext context)
 {
     Table   = table;
     Columns = columns;
     Context = context;
 }
Example #10
0
        public override void CommitChanges(IEnumerable entities, TableAttribute table, IColumnInfoCollection columns)
        {
            using (_connection = OpenConnection())
            {
                lock (_connection)
                {
                    using (_transaction = _connection.BeginTransaction())
                    {
                        try
                        {
                            foreach (IEntityProxy entity in entities)
                            {
                                switch (entity.State)
                                {
                                case EntityState.Added:
                                    Insert(entity, table, columns);
                                    var pk = columns.SingleOrDefault(c => c.IsIdentity);
                                    if (pk != null)
                                    {
                                        var idCommand = string.Format("SELECT CAST(@@IDENTITY AS {0})", pk.ColumnType);
                                        pk.SetValue(entity, ExecuteScalar(idCommand));
                                    }
                                    entity.ClearDirty();
                                    entity.State = EntityState.Unchanged;
                                    break;

                                case EntityState.Changed:
                                    Update(entity, table, columns);
                                    entity.ClearDirty();
                                    entity.State = EntityState.Unchanged;
                                    break;

                                case EntityState.Deleted:
                                    Delete(entity, table, columns);
                                    break;
                                }
                            }
                            _transaction.Commit();
                        }
                        catch (Exception)
                        {
                            _transaction.Rollback();
                            throw;
                        }
                    }
                    _transaction = null;
                }
            }
        }
Example #11
0
 public virtual IColumnInfoCollection UpdateTable <TEntity>(TableAttribute table, IColumnInfoCollection actualColumns, IEnumerable <ColumnInfo> storedColumns)
 {
     if (TableExists(table))
     {
         if (storedColumns != null && !actualColumns.Equals(storedColumns))
         {
             //TODO: check code first option from config
             var tmpTable = new TableAttribute(table.Name + "_tmp", table.Schema);
             CreateTable(tmpTable, actualColumns, false);
             CopyValues(table, tmpTable, actualColumns.Where(c => storedColumns.Any(cc => cc.ColumnName == c.ColumnName)));
             var foreignReferences = GetForeignReferences(table).GroupBy(k => new TableAttribute(k.TableName, k.TableSchema));
             foreach (var group in foreignReferences)
             {
                 RemoveConstraint(group.Key, group.Select(c => c.ConstraintName));
             }
             DeleteTable(table);
             RenameTable(tmpTable, table);
             AppendConstraints(table, actualColumns);
             foreach (var group in foreignReferences)
             {
                 var constraint = group.Select(c => new ConstraintExpression(c.ConstraintName, ExpressionType.Add)
                 {
                     ConstraintType  = ConstraintType.ForeignKey,
                     Columns         = new ColumnExpression(c.SourceColumn),
                     ReferenceTable  = new TableExpression(table),
                     ReferenceColumn = new ColumnExpression(c.TargetColumn)
                 });
                 foreach (var expression in constraint)
                 {
                     AppendConstraints(group.Key, expression);
                 }
             }
         }
     }
     else
     {
         CreateTable(table, actualColumns);
     }
     return(actualColumns);
 }
Example #12
0
 public abstract void BulkInsert(IEnumerable entities, TableAttribute table, IColumnInfoCollection columns);
Example #13
0
 public abstract void CommitChanges(IEnumerable entities, TableAttribute table, IColumnInfoCollection columns);
Example #14
0
        protected virtual void Insert(IEntityProxy entity, TableAttribute table, IColumnInfoCollection columns)
        {
            var insert = CreateInsertExpression(entity, table, columns);

            ExecuteNonQuery(insert);
        }
Example #15
0
        protected InsertExpression CreateInsertExpression(object entity, TableAttribute table, IColumnInfoCollection columns)
        {
            var values = new ValuesExpression();
            var insert = new InsertExpression(new TableExpression(table))
            {
                Values = values
            };
            var type = entity.GetType();

            if (type.Module.ScopeName == "FooBar")
            {
                type = type.BaseType;
            }
            var discriminator = columns.SingleOrDefault(c => c.IsDiscriminatorColumn);

            if (discriminator != null)
            {
                values.AddColumn(discriminator.ToColumnExpression());
                values.AddValue(Expression.Constant(type.FullName));
            }

            foreach (var pi in type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
            {
                try
                {
                    var column = columns.SingleOrDefault(c => c.DescribesProperty(pi));
                    if (column == null)
                    {
                        continue;
                    }

                    var value = pi.GetValue(entity);

                    if (column.IsIdentity)
                    {
                        var defaultValue = Activator.CreateInstance(pi.PropertyType);
                        if (!value.Equals(defaultValue))
                        {
                            insert.IsIdentityInsertEnabled = true;
                        }
                        else
                        {
                            continue;
                        }
                    }

                    values.AddColumn(column.ToColumnExpression());
                    values.AddValue(Expression.Constant(value));
                }
                catch (Exception ex)
                {
                    Debugger.Break();
                }
            }
            return(insert);
        }