Example #1
0
        /// <summary>
        /// Update an entity of Generic Parameter in the corresponding table in the database.
        /// </summary>
        /// <typeparam name="TBusinessEntity">An Entity type to insert the entity object in.</typeparam>
        /// <param name="entity">An entity object to be updated in the table corresponding to Entity type.</param>
        /// <returns>New entity object after update it in the database.</returns>
        /// <exception cref="BusinessRuleException">When a constraints on database level is voilated due to current UPDATE statement.</exception>
        /// <exception cref="RepositoryException">When an error on the database level is occurred and couldn't be recovered.</exception>
        public virtual TBusinessEntity Update <TBusinessEntity>(TBusinessEntity entity)
            where TBusinessEntity : class, new()
        {
            try
            {
                using (ShoppingListContext context = new ShoppingListContext())
                {
                    TBusinessEntity updatedEntity = context.UpdateGraph <TBusinessEntity>(entity);

                    int erc = context.SaveChanges();

                    var result = erc > 0 ? updatedEntity : null;

                    if (result != null)
                    {
                        // update the generation
                        Cache.NextGeneration <TBusinessEntity>();
                    }

                    return(result);
                }
            }
            catch (Exception ex)
            {
                throw ThrowHelper.ReThrow <TBusinessEntity>(ex);
            }
        }
Example #2
0
        /// <summary>
        /// Delete an entity of Generic Parameter from the corresponding table in the database.
        /// </summary>
        /// <typeparam name="TBusinessEntity">An Entity type to delete the entity object from.</typeparam>
        /// <param name="entity">An entity object to be deleted from the table corresponding to Entity type.</param>
        /// <returns>True, if object deleted successfully. False, otherwise.</returns>
        /// <exception cref="BusinessRuleException">When a constraints on database level is voilated due to current DELETE statement.</exception>
        /// <exception cref="RepositoryException">When an error on the database level is occurred and couldn't be recovered.</exception>
        public virtual bool Delete <TBusinessEntity>(TBusinessEntity entity)
            where TBusinessEntity : class, new()
        {
            try
            {
                using (ShoppingListContext context = new ShoppingListContext())
                {
                    context.Set <TBusinessEntity>().Attach(entity);
                    context.Set <TBusinessEntity>().Remove(entity);

                    int erc = context.SaveChanges();

                    var result = erc > 0;

                    if (result == true)
                    {
                        // update the generation
                        Cache.NextGeneration <TBusinessEntity>();
                    }

                    return(result);
                }
            }
            catch (Exception ex)
            {
                throw ThrowHelper.ReThrow <TBusinessEntity>(ex);
            }
        }
Example #3
0
        /// <summary>
        /// Delete entities of Generic Parameter from the corresponding table in the database.
        /// </summary>
        /// <typeparam name="TBusinessEntity">An Entity type to delete the entity object from.</typeparam>
        /// <param name="entities">An entities objects to be deleted from the table corresponding to Entity type.</param>
        /// <returns>True, if object deleted successfully. False, otherwise.</returns>
        /// <exception cref="BusinessRuleException">When a constraints on database level is voilated due to current DELETE statement.</exception>
        /// <exception cref="RepositoryException">When an error on the database level is occurred and couldn't be recovered.</exception>
        public bool Delete <TBusinessEntity>(IEnumerable <TBusinessEntity> entities)
            where TBusinessEntity : class, new()
        {
            try
            {
                using (ShoppingListContext context = new ShoppingListContext())
                {
                    foreach (TBusinessEntity item in entities)
                    {
                        var i = context.UpdateGraph(item);
                        context.Set <TBusinessEntity>().Attach(i);
                        context.Set <TBusinessEntity>().Remove(i);
                    }

                    int erc = context.SaveChanges();

                    var result = erc > 0;

                    if (result == true)
                    {
                        // update the generation
                        Cache.NextGeneration <TBusinessEntity>();
                    }

                    return(result);
                }
            }
            catch (Exception ex)
            {
                throw ThrowHelper.ReThrow <TBusinessEntity>(ex);
            }
        }
 /// <summary>
 /// Returns single BusinessObject of table that satisfies the given <paramref name="id"/> or a null if no such element is found.
 /// </summary>
 /// <typeparam name="TBusinessEntity">The type of BusinessObject of source table.</typeparam>
 /// <param name="id">Id of the BusinessObject.</param>
 /// <returns>BusinessObject the satisfy the <paramref name="id"/>.</returns>
 /// <exception cref="RepositoryException">When an error on the database level is occurred and couldn't be recovered.</exception>
 public TBusinessEntity SingleOrDefault <TBusinessEntity>(int id)
     where TBusinessEntity : class, new()
 {
     try
     {
         using (ShoppingListContext context = new ShoppingListContext())
             return(context.Set <TBusinessEntity>().Find(id));
     }
     catch (Exception ex)
     {
         throw ThrowHelper.ReThrow <TBusinessEntity>(ex);
     }
 }
 /// <summary>
 /// Returns record count of table that satisfy the given <paramref name="constraints"/>.
 /// </summary>
 /// <typeparam name="TBusinessEntity">The type of BusinessObject of source table.</typeparam>
 /// <param name="constraints">QueryConstraints object to be satisfied.</param>
 /// <returns>The number of elements in the table that satisfies the given <paramref name="constraints"/>.</returns>
 /// <exception cref="RepositoryException">When an error on the database level is occurred and couldn't be recovered.</exception>
 public int GetCount <TBusinessEntity>(IQueryConstraints <TBusinessEntity> constraints)
     where TBusinessEntity : class, new()
 {
     try
     {
         using (ShoppingListContext context = new ShoppingListContext())
             return(context.Set <TBusinessEntity>()
                    .Count(constraints.Predicate));
     }
     catch (Exception ex)
     {
         throw ThrowHelper.ReThrow <TBusinessEntity>(ex);
     }
 }
 /// <summary>
 /// Returns custom graph of single BusinessObject of table that satisfies a specified <see cref="IQueryConstraints{T}"/> or null if no such element is found.
 /// </summary>
 /// <typeparam name="TBusinessEntity">The type of BusinessObject of source table.</typeparam>
 /// <param name="constraints">QueryConstraints object to be satisfied.</param>
 /// <returns>BusinessObject the satisfy the <paramref name="constraints"/>.</returns>
 /// <exception cref="RepositoryException">When an error on the database level is occurred and couldn't be recovered.</exception>
 public TBusinessEntity SingleOrDefault <TBusinessEntity>(IQueryConstraints <TBusinessEntity> constraints)
     where TBusinessEntity : class, new()
 {
     try
     {
         using (ShoppingListContext context = new ShoppingListContext())
             return(context.Set <TBusinessEntity>()
                    .ToSearchResult <TBusinessEntity>(constraints)
                    .Items
                    .FirstOrDefault());
     }
     catch (Exception ex)
     {
         throw ThrowHelper.ReThrow <TBusinessEntity>(ex);
     }
 }
        /// <summary>
        /// Returns full graph of single BusinessObject of table that satisfies the given <paramref name="id"/> or null if no such element is found.
        /// </summary>
        /// <typeparam name="TBusinessEntity">The type of BusinessObject of source table.</typeparam>
        /// <param name="id">Id of the BusinessObject.</param>
        /// <returns>BusinessObject the satisfy the <paramref name="id"/>.</returns>
        /// <exception cref="RepositoryException">When an error on the database level is occurred and couldn't be recovered.</exception>
        public TBusinessEntity SingleOrDefaultWithGraph <TBusinessEntity>(int id)
            where TBusinessEntity : class, new()
        {
            try
            {
                using (ShoppingListContext context = new ShoppingListContext())
                {
                    var primaryKeyPredicate = CreatePredicate <TBusinessEntity>(context, id);

                    return(context.LoadAggregate(primaryKeyPredicate));
                }
            }
            catch (Exception ex)
            {
                throw ThrowHelper.ReThrow <TBusinessEntity>(ex);
            }
        }
        /// <summary>
        /// Returns <see cref="IQueryResult{T}"/> that satisfy the given <paramref name="constraints"/> on the table.
        /// </summary>
        /// <typeparam name="TBusinessEntity">The type of BusinessObject of source table.</typeparam>
        /// <param name="constraints">QueryConstraints object to be satisfied.</param>
        /// <returns>The result records that satisfy the given <paramref name="constraints"/>.</returns>
        /// <exception cref="RepositoryException">When an error on the database level is occurred and couldn't be recovered.</exception>
        public IQueryResult <TBusinessEntity> Find <TBusinessEntity>(IQueryConstraints <TBusinessEntity> constraints)
            where TBusinessEntity : class, new()
        {
            try
            {
                using (ShoppingListContext context = new ShoppingListContext())
                {
                    IQueryResult <TBusinessEntity> results = null;

                    // get the appropriate cache key for this query
                    string key = Cache.CacheKey(constraints);

                    // check if it's in the cache already
                    if (!Cache.Provider.TryGet(key, out results))
                    {
                        Debug.WriteLine($"NOT FOUND cache for: {key}");

                        // if not, then run the query
                        results = context.Set <TBusinessEntity>().ToSearchResult(constraints);

                        // and cache the results for next time
                        Cache.Provider.Set(key, results);
                    }
                    else
                    {
                        Debug.WriteLine($"Found cache for: {key}");
                    }

                    // return the results either from cache or that were just run
                    return(results);
                }
            }
            catch (Exception ex)
            {
                throw ThrowHelper.ReThrow <TBusinessEntity>(ex);
            }
        }
        private Expression <Func <TBusinessEntity, bool> > CreatePredicate <TBusinessEntity>(ShoppingListContext context, int id)
        {
            var entityType = typeof(TBusinessEntity);

            var metadata = ((IObjectContextAdapter)context).ObjectContext.MetadataWorkspace
                           .GetItems <EntityType>(DataSpace.OSpace)
                           .SingleOrDefault(p => p.FullName == entityType.FullName);

            if (metadata == null)
            {
                throw new InvalidOperationException($"The type {entityType.FullName} is not known to the DbContext.");
            }

            var keyProperties = metadata.KeyMembers
                                .Select(k => entityType.GetProperty(k.Name, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public))
                                .ToList();

            ParameterExpression parameter  = Expression.Parameter(entityType);
            Expression          expression = CreateEqualsExpression(id, keyProperties[0], parameter);

            //for (int i = 1; i < keyProperties.Count; i++)
            //{
            //    expression = Expression.And(expression, CreateEqualsExpression(entity, keyProperties[i], parameter));
            //}

            return(Expression.Lambda <Func <TBusinessEntity, bool> >(expression, parameter));
        }