示例#1
0
        /// <summary>
        /// 根据实体的状态,插入或更新实体对象。
        /// </summary>
        /// <param name="entity">要保存的实体对象。</param>
        /// <returns>影响的实体数。</returns>
        public int InsertOrUpdate(TEntity entity)
        {
            Guard.ArgumentNull(entity, nameof(entity));

            var properties = PropertyUnity.GetPrimaryProperties(typeof(TEntity));
            var isNew      = entity.EntityState == EntityState.Attached;

            if (isNew && properties.Any(s => !PropertyValue.IsEmptyOrDefault(entity.GetValue(s))))
            {
                var parExp    = Expression.Parameter(typeof(TEntity), "s");
                var equalExp  = properties.Select(s => Expression.Equal(Expression.MakeMemberAccess(parExp, s.Info.ReflectionInfo), Expression.Constant(entity.GetValue(s)))).Aggregate(Expression.And);
                var lambdaExp = Expression.Lambda <Func <TEntity, bool> >(equalExp, parExp);
                isNew = !this.Any(lambdaExp);
            }

            if (options.NotifyEvents)
            {
                if (isNew)
                {
                    return(EntityPersistentSubscribeManager.OnCreate(entity, () => repositoryProxy.Insert(entity)));
                }
                else
                {
                    return(EntityPersistentSubscribeManager.OnUpdate(entity, () => repositoryProxy.Update(entity)));
                }
            }

            return(isNew ? repositoryProxy.Insert(entity) : repositoryProxy.Update(entity));
        }
示例#2
0
        /// <summary>
        /// 异步的,根据实体的状态,插入或更新实体对象。
        /// </summary>
        /// <param name="entity">要保存的实体对象。</param>
        /// <param name="cancellationToken">取消操作的通知。</param>
        /// <returns>影响的实体数。</returns>
        public async Task <int> InsertOrUpdateAsync(TEntity entity, CancellationToken cancellationToken = default)
        {
            Guard.ArgumentNull(entity, nameof(entity));

            var properties = PropertyUnity.GetPrimaryProperties(typeof(TEntity));
            var isNew      = entity.EntityState == EntityState.Attached;

            if (isNew && properties.Any(s => !PropertyValue.IsEmptyOrDefault(entity.GetValue(s))))
            {
                var parExp    = Expression.Parameter(typeof(TEntity), "s");
                var equalExp  = properties.Select(s => Expression.Equal(Expression.MakeMemberAccess(parExp, s.Info.ReflectionInfo), Expression.Constant(entity.GetValue(s)))).Aggregate(Expression.And);
                var lambdaExp = Expression.Lambda <Func <TEntity, bool> >(equalExp, parExp);
                isNew = !this.Any(lambdaExp);
            }

            return(await(isNew ? InsertAsync(entity, cancellationToken) : UpdateAsync(entity, cancellationToken)));
        }