/// <summary>
        /// auto update create at, by, update at, mod by
        /// </summary>
        /// <param name="user">user.name</param>
        /// <returns></returns>
        //public int SaveChanges(/*string user*/)
        //{
        //    //RenewMacroColumn(user);
        //    return SaveChanges();
        //}
        /// <summary>
        /// base save changes
        /// </summary>
        /// <returns></returns>
        //public override int SaveChanges()
        //{
        //    try
        //    {
        //        return base.SaveChanges();
        //    }
        //    catch (DbEntityValidationException ex)
        //    {
        //        Exception raise = ex;
        //        foreach (var validationErrors in ex.EntityValidationErrors)
        //        {
        //            foreach (var validationError in validationErrors.ValidationErrors)
        //            {
        //                string message = string.Format("{0}:{1}",
        //                    validationErrors.Entry.Entity.ToString(),
        //                    validationError.ErrorMessage);
        //                // raise a new exception nesting
        //                // the current instance as InnerException
        //                raise = new InvalidOperationException(message, raise);
        //            }
        //        }
        //        return -1;
        //    }
        //}


        //protected void RenewMacroColumn(string user)
        //{
        //    foreach (var dbEntry in this.ChangeTracker.Entries())
        //    {
        //        switch (dbEntry.State)
        //        {

        //            case EntityState.Added:
        //                CreateWithValues(dbEntry, "GID", System.Guid.NewGuid());
        //                CreateWithValues(dbEntry, "CreatedAt", System.DateTime.Now);

        //                CreateWithValues(dbEntry, "ModBy", user);
        //                CreateWithValues(dbEntry, "UpdatedAt", System.DateTime.Now);
        //                break;

        //            case EntityState.Modified:

        //                CreateWithValues(dbEntry, "ModBy", user);
        //                CreateWithValues(dbEntry, "UpdatedAt", System.DateTime.Now);
        //                break;
        //        }
        //    }
        //}

        private void CreateWithValues(System.Data.Entity.Infrastructure.DbEntityEntry dbEntry, string propertyName, object value)
        {
            if (dbEntry.CurrentValues.PropertyNames.Any(x => x == propertyName))
            {
                dbEntry.Property(propertyName).CurrentValue = value;
            }
        }
Ejemplo n.º 2
0
        protected override DbEntityValidationResult ValidateEntity(System.Data.Entity.Infrastructure.DbEntityEntry entityEntry, IDictionary <object, object> items)
        {
            if (typeof(System.ComponentModel.DataAnnotations.IValidatableObject).IsAssignableFrom(entityEntry.Entity.GetType()))
            {
                var type = entityEntry.Entity.GetType();
                if (IsProxy(type))
                {
                    type = entityEntry.Entity.GetType().BaseType;
                }

                MethodInfo method  = this.GetType().GetMethod("GetNavigationProperties");
                MethodInfo generic = method.MakeGenericMethod(type);
                var        navigationProperties = generic.Invoke(this, new object[] { entityEntry.Entity }) as List <PropertyInfo>;

                foreach (var property in navigationProperties)
                {
                    if (typeof(System.Collections.IEnumerable).IsAssignableFrom(property.PropertyType))
                    {
                        this.Entry(entityEntry.Entity).Collection(property.Name);
                    }
                    else
                    {
                        this.Entry(entityEntry.Entity).Reference(property.Name);
                    }
                }

                var result = new DbEntityValidationResult(entityEntry, ((IValidatableObject)entityEntry.Entity).Validate(new System.ComponentModel.DataAnnotations.ValidationContext(entityEntry.Entity)).Select(x => new DbValidationError(x.MemberNames.FirstOrDefault(), x.ErrorMessage)));
                if (!result.IsValid)
                {
                    return(result);
                }
            }

            return(base.ValidateEntity(entityEntry, items));
        }
Ejemplo n.º 3
0
        public static async Task <EntityEntry> RefreshAsync(this EntityEntry tracking, RefreshConflict refreshMode)
        {
            switch (refreshMode)
            {
            case RefreshConflict.StoreWins:
                {
                    await tracking.ReloadAsync();

                    break;
                }

            case RefreshConflict.ClientWins:
                {
                    PropertyValues databaseValues = await tracking.GetDatabaseValuesAsync();

                    if (databaseValues == null)
                    {
                        tracking.State = EntityState.Detached;
                    }
                    else
                    {
                        tracking.OriginalValues.SetValues(databaseValues);
                    }
                    break;
                }

            case RefreshConflict.MergeClientAndStore:
                {
                    PropertyValues databaseValues = await tracking.GetDatabaseValuesAsync();

                    if (databaseValues == null)
                    {
                        tracking.State = EntityState.Detached;
                    }
                    else
                    {
                        PropertyValues originalValues = tracking.OriginalValues.Clone();
#if !EF
                        originalValues.SetValues(tracking.OriginalValues);
#endif
                        tracking.OriginalValues.SetValues(databaseValues);
#if EF
                        databaseValues.PropertyNames
                        .Where(property => !object.Equals(originalValues[property], databaseValues[property]))
                        .ForEach(property => tracking.Property(property).IsModified = false);
#else
                        databaseValues.Properties
                        .Where(property => !object.Equals(originalValues[property.Name], databaseValues[property.Name]))
                        .ForEach(property => tracking.Property(property.Name).IsModified = false);
#endif
                    }
                    break;
                }
            }
            return(tracking);
        }
Ejemplo n.º 4
0
        private void SetUpdateTime(System.Data.Entity.Infrastructure.DbEntityEntry entry)
        {
            if (entry.State != EntityState.Added && entry.State != EntityState.Modified)
            {
                return;
            }

            var  entity = entry.Entity;
            Type type   = entity.GetType();
            var  pi     = type.GetProperty("UpdateTime");

            if (pi != null)
            {
                pi.SetValue(entity, DBTimeHelper.DBNowTime(this));
            }
        }
Ejemplo n.º 5
0
        public void Edit(TEntity model, string[] propertys)

        {
            if (model == null)
            {
                throw new Exception(" 实体不能为空");
            }
            if (propertys.Any() == false)
            {
                throw new Exception("要修改的属性至少有一个");
            }
            // 2.0 将 model 追加到EF容器
            System.Data.Entity.Infrastructure.DbEntityEntry entry = db.Entry(model);
            entry.State = System.Data.EntityState.Unchanged;
            foreach (var item in propertys)
            {
                entry.Property(item).IsModified = true;
            }
            //3.0 关闭EF对于实体的合法性验证参数
            db.Configuration.ValidateOnSaveEnabled = false;
        }
Ejemplo n.º 6
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="model">没有被ef容器管理的</param>
        /// <param name="propertyNames"></param>
        public void Edit(TEntity model, string[] propertyNames)
        {
            //1.0 合法性验证
            if (model == null)
            {
                throw new Exception("Edit中的参数model不能为null");
            }

            if (propertyNames == null || propertyNames.Any() == false)
            {
                throw new Exception("Edit中的参数propertyNames至少要有一个属性");
            }

            //2.0 将model追加到EF容器中
            System.Data.Entity.Infrastructure.DbEntityEntry entry = db.Entry(model);
            entry.State = System.Data.EntityState.Unchanged;
            foreach (var item in propertyNames)
            {
                entry.Property(item).IsModified = true;
            }

            //3.0 关闭EF的实体属性合法性验证
            db.Configuration.ValidateOnSaveEnabled = false;
        }
Ejemplo n.º 7
0
 /// <summary>
 /// The ValidateEntity method override that addes this context to instance to the validation items.
 /// </summary>
 /// <param name="entityEntry">The entity entry to validate.</param>
 /// <param name="items">The items that will contain the DbContext.</param>
 /// <returns>The validation results.</returns>
 protected override System.Data.Entity.Validation.DbEntityValidationResult ValidateEntity(System.Data.Entity.Infrastructure.DbEntityEntry entityEntry, IDictionary <object, object> items)
 {
     items.Add(VALIDATABLE_CONTEXT_KEY, this);
     return(base.ValidateEntity(entityEntry, items));
 }
Ejemplo n.º 8
0
 /// <summary>
 /// 在保存之前处理每一个Entry;默认不进行任何处理;
 /// </summary>
 public virtual void HandleOneTrackerEntityBeforeSaveChange(EntityEntry aEntity)
 {
 }
Ejemplo n.º 9
0
        protected override System.Data.Entity.Validation.DbEntityValidationResult ValidateEntity(System.Data.Entity.Infrastructure.DbEntityEntry entityEntry, IDictionary <object, object> items)
        {
            // バリデーションは、エンティティモデル単位で行うこと

            if (entityEntry.Entity is Content)
            {
                var list   = new List <System.Data.Entity.Validation.DbValidationError>();
                var entity = entityEntry.Entity as Content;

                // Title
                if (entityEntry.CurrentValues.GetValue <string>("Title") == "")
                {
                    list.Add(new System.Data.Entity.Validation.DbValidationError("Title", "Title is required"));
                }

                // Starrating (0~5)
                int iStarrating = entityEntry.CurrentValues.GetValue <int>("Starrating");
                if (iStarrating < 0 || iStarrating > 5)
                {
                    list.Add(new System.Data.Entity.Validation.DbValidationError("Starrating", "設定範囲外"));
                }

                return(new System.Data.Entity.Validation.DbEntityValidationResult(entityEntry, list));
            }
            else if (entityEntry.Entity is Category)
            {
                var list   = new List <System.Data.Entity.Validation.DbValidationError>();
                var entity = entityEntry.Entity as Category;

                if (entityEntry.State == EntityState.Deleted)
                {
                    if (entity.Id == 1L)
                    {
                        list.Add(new System.Data.Entity.Validation.DbValidationError("Category.ID", "ID:1は削除できません"));
                    }
                }

                return(new System.Data.Entity.Validation.DbEntityValidationResult(entityEntry, list));
            }


            return(base.ValidateEntity(entityEntry, items));
        }