예제 #1
0
        public static bool Merge <T>(IEntity entity, bool bypassConflicts = false) where T : IEntity, new()
        {
            bool ret = true;

            try
            {
                bool isNew = true;
                foreach (ElementBaseData ebd in entity.__Elements.Where(ebd => ebd.SqlDbIsPrimaryKey).ToList())
                {
                    if ((ebd.TypeName.Equals("int") && int.Parse(ebd.Data.ToString()) != 0) || (ebd.TypeName.Equals("Guid") && !Guid.Parse(ebd.Data.ToString()).Equals(Guid.Empty)))
                    {
                        isNew = false;
                        break;
                    }
                }

                if (isNew)
                {
                    CRUDActions.Create <T>(entity);
                    return(true);
                }

                IEntity copy = new T();
                copy.ConnectionString = entity.ConnectionString;
                entity.__Elements.Where(ebd => ebd.SqlDbIsPrimaryKey).ToList().ForEach(ebd => copy.__Elements.Find(c => c.Name.Equals(ebd.Name)).Data = ebd.Data);

                CRUDActions.Retrieve <T>(copy);

                if (copy.Notifications.Count == 0)
                {
                    if (entity.__Memento.Count == 0)
                    {
                        long fieldsToSave = entity.Compare(copy);
                        CRUDActions.Merge <T>(entity, fieldsToSave);
                    }
                    else
                    {
                        long fieldsToSave = entity.Compare();
                        if (fieldsToSave == 0)
                        {
                            return(false);
                        }

                        SetWarnings(entity, copy);

                        if (!bypassConflicts)
                        {
                            SetConflicts(entity, copy);
                            ret = entity.CRUDConflict.Fields.Count == 0;
                        }

                        if (ret)
                        {
                            entity.__Elements.ForEach(e => UpdateField(e, copy, fieldsToSave));
                            CRUDActions.Merge <T>(copy, fieldsToSave);

                            entity.__Elements.Where(e => !e.IsCollection).ToList().ForEach(e => SaveCollection(e, copy));
                        }
                    }
                }
                else
                {
                    CRUDActions.Create <T>(entity);
                }
            }
            catch (System.Exception ex)
            {
                entity.Exceptions.Add(new EntityException(1, ex.Message, ex));
            }
            return(ret);
        }