Exemplo n.º 1
0
        /// <summary>
        /// 将实体对象更新到数据库,调用该方法时实体对象必须具备主键属性
        /// </summary>
        /// <param name="object">实体对象</param>
        public virtual int Update(object @object)
        {
            IEntityObject entity = (IEntityObject)@object;

            Type elementType = @object.GetType().BaseType;

            IUpdateable updateable = this.factory.CreateUpdateProvider(this).CreateUpdate(elementType);

            var properties = @object.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);

            properties.Each(property =>
            {
                if (property.IsPrimaryKey() == false)
                {
                    if (entity.ChangedProperties.Contains(property.Name))
                    {
                        ParameterExpression pe = Expression.Parameter(@object.GetType(), "s");
                        MemberExpression me    = Expression.MakeMemberAccess(pe, property);

                        updateable.Set(me, property.EmitGetValue(@object));
                    }
                }
                else
                {
                    ParameterExpression pe = Expression.Parameter(@object.GetType(), "s");
                    MemberExpression me    = Expression.MakeMemberAccess(pe, property);
                    ConstantExpression ce  = Expression.Constant(property.EmitGetValue(@object), property.PropertyType);
                    BinaryExpression be    = Expression.Equal(me, ce);

                    updateable = updateable.Where(be);
                }
            });

            return(updateable.Execute(elementType));
        }
Exemplo n.º 2
0
        public static int Execute(this IUpdateable update, string message = null)
        {
            if (message != null)
            {
                return(SafeConsole.WaitRows(message == "auto" ? UnsafeMessage(update) : message,
                                            () => update.Execute(message: null)));
            }

            using (HeavyProfiler.Log("DBUnsafeUpdate", () => update.EntityType.TypeName()))
            {
                if (update == null)
                {
                    throw new ArgumentNullException("update");
                }

                using (Transaction tr = new Transaction())
                {
                    Schema.Current.OnPreUnsafeUpdate(update);
                    int rows = DbQueryProvider.Single.Update(update, sql => (int)sql.ExecuteScalar());

                    return(tr.Commit(rows));
                }
            }
        }