Beispiel #1
0
        /// <summary>
        /// 将一个实体序列转换为 <see cref="DataTable"/> 对象。
        /// </summary>
        /// <typeparam name="TEntity">实体的类型。</typeparam>
        /// <param name="source">一个包含实体对象的序列。</param>
        /// <param name="tableName">指定 <see cref="DataTable"/> 的表名,如果忽略该参数,则根据实体的类型进行获取。</param>
        /// <param name="changedOnly">仅仅转换状态改变的实体。</param>
        /// <returns></returns>
        public static DataTable ToDataTable <TEntity>(this IEnumerable <TEntity> source, string tableName = null, bool changedOnly = false) where TEntity : IEntity
        {
            if (source.IsNullOrEmpty())
            {
                return(null);
            }
            var entityType = source.FirstOrDefault().GetType();
            var properties = new List <IProperty>(PropertyUnity.GetPersistentProperties(entityType));

            if (string.IsNullOrEmpty(tableName))
            {
                var metadata = EntityMetadataUnity.GetEntityMetadata(entityType);
                tableName = metadata.TableName;
            }

            var table = new DataTable(tableName);
            var keys  = CreateTableColumns(table, properties);

            var extendList = source.As <IEntitySetInternalExtension>();

            if (extendList != null && changedOnly)
            {
                FillDataTableRows(table, extendList, properties, keys.Length > 0);
            }
            else
            {
                FillDataTableRows(table, source, properties, keys.Length > 0);
            }
            if (keys.Length > 0)
            {
                var con = new UniqueConstraint(keys, true);
                table.Constraints.Add(con);
            }
            return(table);
        }
Beispiel #2
0
        /// <summary>
        /// 为实体对象应用默认值。
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static IEntity ApplyDefaultValue(this IEntity entity)
        {
            foreach (var property in PropertyUnity.GetPersistentProperties(entity.EntityType))
            {
                if (!PropertyValue.IsEmpty(property.Info.DefaultValue))
                {
                    entity.InitializeValue(property, property.Info.DefaultValue);
                }
            }

            return(entity);
        }
Beispiel #3
0
        /// <summary>
        /// 使用指定的实体的属性集来构造一个 <see cref="DataTable"/>,<see cref="DataTable"/> 里的列与实体属性一一对应。
        /// </summary>
        /// <param name="entityType">实体的类型。</param>
        /// <returns></returns>
        private static DataTable Construct(Type entityType)
        {
            Guard.ArgumentNull(entityType, "entityType");
            var metadata = EntityMetadataUnity.GetEntityMetadata(entityType);
            var table    = new DataTable(metadata.TableName);

            foreach (var property in PropertyUnity.GetPersistentProperties(entityType))
            {
                table.Columns.Add(property.ToDataColumn());
            }

            return(table);
        }
Beispiel #4
0
        /// <summary>
        /// 设置默认值。
        /// </summary>
        /// <param name="entity"></param>
        protected virtual void SetDefaultValue(TEntity entity)
        {
            var isNotCompiled = entity.EntityType.IsNotCompiled();

            foreach (var property in PropertyUnity.GetPersistentProperties(EntityType))
            {
                var isModify = isNotCompiled ? !PropertyValue.IsEmpty(entity.GetValue(property)) : entity.IsModified(property.Name);
                if (!isModify && !PropertyValue.IsEmpty(property.Info.DefaultValue))
                {
                    entity.SetValue(property, property.Info.DefaultValue.TryAllotValue(property.Type, property.Info.DefaultValueFormatter));
                }
            }
        }
Beispiel #5
0
        private bool InternalCreate(IEntity entity)
        {
            var parameters = new ParameterCollection();
            var context    = CreateContext(parameters);
            var sql        = EntityPersistentQueryBuilder.BuidCreateQuery(context, entity);

            if (!sql.IsNullOrEmpty())
            {
                var rootType = entity.EntityType.GetRootType();

                //找出自增长序列的属性
                var incProperty = PropertyUnity.GetPersistentProperties(rootType).FirstOrDefault(s => s.Info.GenerateType == IdentityGenerateType.AutoIncrement);

                if (incProperty != null)
                {
                    if (!string.IsNullOrEmpty(context.Syntax.IdentitySelect))
                    {
                        //获得当前插入的自增长序列值
                        var identitySelect = context.Syntax.IdentitySelect;
                        if (!identitySelect.StartsWith(";"))
                        {
                            identitySelect = ";" + identitySelect;
                        }

                        var incValue = PropertyValueHelper.NewValue(context.Database.ExecuteScalar <int>(sql + identitySelect, context.Parameters));
                        entity.InternalSetValue(incProperty, incValue);
                        return(!incValue.IsNullOrEmpty());
                    }
                    else
                    {
                        //使用生成器生成值
                        var generator = context.Database.Provider.GetService <IGeneratorProvider>();
                        if (generator != null)
                        {
                            var metadata = EntityMetadataUnity.GetEntityMetadata(entityType);
                            var inc      = generator.GenerateValue(context.Database, context.Environment == null ? metadata.TableName : context.Environment.GetVariableTableName(metadata), incProperty.Info.FieldName);
                            entity.InternalSetValue(incProperty, inc);

                            parameters.Clear();
                            sql = EntityPersistentQueryBuilder.BuidCreateQuery(context, entity);

                            return(context.Database.ExecuteNonQuery(sql, context.Parameters) > 0);
                        }
                    }
                }

                return(database.ExecuteNonQuery(sql, parameters) > 0);
            }

            return(false);
        }
Beispiel #6
0
        /// <summary>
        /// 将一个实体对象添加到 <see cref="DataTable"/> 对象里,该 <see cref="DataTable"/> 的结构必须保证与实体结构相符。
        /// </summary>
        /// <param name="entity">当前的实体对象。</param>
        /// <param name="table">一个使用 <see cref="Construct"/> 构造的 <see cref="DataTable"/>。</param>
        public static void Putin(this IEntity entity, DataTable table)
        {
            Guard.ArgumentNull(entity, "entity");
            Guard.ArgumentNull(table, "table");

            var properties = PropertyUnity.GetPersistentProperties(entity.EntityType)
                             .Where(s => table.Columns.Contains(s.Name)).ToList();

            var count = properties.Count;
            var data  = new object[count];

            for (var i = 0; i < count; i++)
            {
                var value = entity.InternalGetValue(properties[i]);
                data[i] = PropertyValue.IsNullOrEmpty(value) ? DBNull.Value : value.GetStorageValue();
            }

            table.Rows.Add(data);
        }
Beispiel #7
0
        /// <summary>
        /// 构造创建表的语句。
        /// </summary>
        /// <param name="entityType">实体类型。</param>
        /// <param name="syntax">语法服务。</param>
        /// <param name="tableName">数据表名称。</param>
        /// <returns></returns>
        private static string BuildTableScript(Type entityType, ISyntaxProvider syntax, string tableName)
        {
            var sb = new StringBuilder();

            sb.AppendFormat("create table {0}\n(\n", tableName);

            //获取实体类型中所有可持久化的属性,不包含引用类型的属性
            var properties        = PropertyUnity.GetPersistentProperties(entityType).ToArray();
            var primaryPeoperties = PropertyUnity.GetPrimaryProperties(entityType).ToArray();
            var count             = properties.Length;

            for (var i = 0; i < count; i++)
            {
                var property = properties[i];
                sb.AppendFormat(" {0}", property.Info.FieldName);

                //数据类型及长度精度等
                sb.AppendFormat(" {0}", syntax.Column((DbType)property.Info.DataType,
                                                      property.Info.Length,
                                                      property.Info.Precision,
                                                      property.Info.Scale));

                //自增
                if (property.Info.GenerateType == IdentityGenerateType.AutoIncrement &&
                    !string.IsNullOrEmpty(syntax.IdentityColumn))
                {
                    sb.AppendFormat(" {0}", syntax.IdentityColumn);
                }

                //不可空
                if (!property.Info.IsNullable)
                {
                    sb.AppendFormat(" not null");
                }

                //默认值
                if (!PropertyValue.IsEmpty(property.Info.DefaultValue))
                {
                    if (property.Type == typeof(string))
                    {
                        sb.AppendFormat(" default '{0}'", property.Info.DefaultValue);
                    }
                    else if (property.Type.IsEnum)
                    {
                        sb.AppendFormat(" default {0}", (int)property.Info.DefaultValue);
                    }
                    else if (property.Type == typeof(bool) || property.Type == typeof(bool?))
                    {
                        sb.AppendFormat(" default {0}", (bool)property.Info.DefaultValue ? 1 : 0);
                    }
                    else
                    {
                        sb.AppendFormat(" default {0}", property.Info.DefaultValue);
                    }
                }

                if (i != count - 1)
                {
                    sb.Append(",");
                }

                sb.AppendLine();
            }

            //主键
            if (primaryPeoperties.Length > 0)
            {
                sb.Append(",");
                sb.AppendFormat("constraint PK_{0} primary key (", tableName);

                for (var i = 0; i < primaryPeoperties.Length; i++)
                {
                    if (i != 0)
                    {
                        sb.Append(",");
                    }

                    sb.Append(primaryPeoperties[i].Info.FieldName);
                }

                sb.Append(")");
            }

            sb.Append(")\n");

            return(sb.ToString());
        }