Exemple #1
0
        public object Post(InsertActivity request)
        {
            var entity = request.ConvertTo <Activity>();

            return(InTransaction(db =>
            {
                Logic.Add(entity);
                return new CommonResponse(Logic.GetById(entity.Id));
            }));
        }
        public void Save <T>(T item) where T : IMongoEntity
        {
            bool writeLog   = DefaultWriteLog;
            bool preprocess = DefaultPreprocess;
            Type type       = typeof(T);
            CollectionSaveAttribute attr = GetSaveAttribute(type);

            if (attr != null)
            {
                writeLog   = attr.WriteLog;
                preprocess = attr.Preprocess;
            }

            if (preprocess && objectPreprocessor != null)
            {
                objectPreprocessor.Preprocess(item);
            }

            ActivityType activityType;
            T            oldValue = default(T);

            if (item.Id == null)
            {
                GetCollection <T>().InsertOne(item);
                activityType = ActivityType.Insert;
            }
            else
            {
                if (writeLog)
                {
                    oldValue = FindById <T>(item.Id);
                }
                GetCollection <T>().ReplaceOne(t => t.Id == item.Id, item, new ReplaceOptions {
                    IsUpsert = true
                });
                activityType = ActivityType.Update;
            }
            if (writeLog)
            {
                string username = GetUserNameFunc();
                if (activityType == ActivityType.Insert)
                {
                    var insertActivity = new InsertActivity(username)
                    {
                        CollectionName = GetCollectionName(type), ObjId = item.Id
                    };
                    Save((UserActivity)insertActivity);
                }
                else
                {
                    UpdateActivity update = new UpdateActivity(username)
                    {
                        CollectionName = GetCollectionName(type), ObjId = oldValue.Id
                    };
                    update.SetDiff(oldValue, item);
                    if (update.Diff.Count > 0)
                    {
                        Save((UserActivity)update);
                    }
                }
            }
        }