Пример #1
0
 public GenericRepository(DropItContext ctx)
 {
     this.context = ctx;
     this.dbSet   = ctx.Set <TEntity>();
 }
Пример #2
0
        public virtual TEntity AddOrUpdate(TEntity entity)
        {
            DateTime now         = DateTime.Now;
            var      currentUser = GetCurrentUser();

            var propsEntity = typeof(TEntity).GetProperties();

            var entityId         = propsEntity.FirstOrDefault(p => p.Name.Equals(typeof(TEntity).Name + "Id")).GetValue(entity, null);
            var createdDate      = propsEntity.FirstOrDefault(p => p.Name.Equals("CreatedDate"));
            var lastModifiedDate = propsEntity.FirstOrDefault(p => p.Name.Equals("ModifiedDate"));
            var createdBy        = propsEntity.FirstOrDefault(p => p.Name.Equals("CreatedBy"));
            var lastModifiedBy   = propsEntity.FirstOrDefault(p => p.Name.Equals("LastModifedBy"));

            if ((int)entityId == default(int))
            {
                if (createdDate != null)
                {
                    createdDate.SetValue(entity, now, null);
                }
                if (lastModifiedDate != null)
                {
                    lastModifiedDate.SetValue(entity, now, null);
                }
                if (createdBy != null)
                {
                    createdBy.SetValue(entity, (currentUser != null) ? currentUser.UserId : 1, null);
                }
                if (lastModifiedBy != null)
                {
                    lastModifiedBy.SetValue(entity, (currentUser != null) ? currentUser.UserId : 1, null);
                }
                try
                {
                    return(dbSet.Add(entity));
                }
                catch (Exception e)
                {
                    throw e;
                }
            }
            else
            {
                if (lastModifiedDate != null)
                {
                    lastModifiedDate.SetValue(entity, now, null);
                }
                if (lastModifiedBy != null)
                {
                    lastModifiedBy.SetValue(entity, (currentUser != null) ? currentUser.UserId : 1, null);
                }

                var entry = context.Entry(entity);
                if (entry.State == EntityState.Detached)
                {
                    var     set            = context.Set <TEntity>();
                    TEntity attachedEntity = set.Find(entityId);
                    if (attachedEntity != null)
                    {
                        var attachedEntry = context.Entry(attachedEntity);
                        attachedEntry.CurrentValues.SetValues(entity);
                    }
                    else
                    {
                        entry.State = EntityState.Modified;
                    }
                }
            }

            return(null);
        }