Ejemplo n.º 1
0
        /// <summary>
        /// Изменение записи в базе данных
        /// </summary>
        /// <typeparam name="Entity"></typeparam>
        /// <param name="record">Запись с обновленными значениями</param>
        /// <param name="condition">Услобие в базе данных которое выбирает запись</param>
        /// <returns></returns>
        public static bool Modify <Entity>(Entity record, Expression <Func <Entity, bool> > condition) where Entity : class
        {
            var result = false;
            var exists = false;

            using (var db = new InventoryContext(_connectionString))
            {
                using (var dbTransaction = db.Database.BeginTransaction())
                {
                    try
                    {
                        var EntityTable = db.Set <Entity>();
                        var query       = EntityTable.Where(condition);
                        foreach (var rec in query)
                        {
                            exists = true;
                            var propertyes = EntityClone.GetProperties(typeof(Entity));
                            foreach (var property in propertyes)
                            {
                                property.SetValue(rec, property.GetValue(record));
                            }
                        }

                        if (exists)
                        {
                            db.SaveChanges();
                            dbTransaction.Commit();
                            result = true;
                        }
                    }
                    catch (Exception e)
                    {
                        dbTransaction.Rollback();

                        Console.WriteLine("Невозможно изменить запись в базе данных");
                    }
                }
            }

            return(result);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Добавляем или меняем транзакции в базе
        /// </summary>
        /// <param name="top">Если свойство Id = 0, функция добавляет новую транзакцию. Если в базе уже есть транзакция с тем же Id, вункция изменяет ее.</param>
        /// <param name="body"></param>
        /// <returns>Если прошло успешно возвращает true</returns>
        public static bool AddOrModifyTransaction(TransactionTopEntity top, List <TransactionListBodyEntity> body)
        {
            if (top == null || body == null)
            {
                return(false);
            }
            bool result = false;
            bool newTop = (top.Id == 0);

            using (var db = new InventoryContext(DatabaseConnection.ConnectionString))
            {
                using (var dbTransaction = db.Database.BeginTransaction())
                {
                    try
                    {
                        int transactionId = top.Id;

                        //Top записи
                        if (!newTop)    //Изменение
                        {
                            var topQuery = db.TransactionTop.Where(p => p.Id == top.Id);
                            foreach (var record in topQuery)
                            {
                                PropertyInfo[] properties = EntityClone.GetProperties(typeof(TransactionTopEntity));
                                foreach (PropertyInfo property in properties)
                                {
                                    property.SetValue(record, property.GetValue(top));
                                }
                            }

                            db.SaveChanges();
                            result = true;
                        }
                        else    //вставить
                        {
                            db.TransactionTop.Add(top);
                            db.SaveChanges();
                            result        = true;
                            transactionId = top.Id;
                        }

                        if (result)
                        {
                            result = false;
                            foreach (var rec in body)
                            {
                                rec.Body.TransactionId = transactionId;
                            }

                            var query = db.TransactionBody.Where(p => p.TransactionId == transactionId);
                            foreach (var rec in query)
                            {
                                var newRec = body.Where(p => p.Body.Id == rec.Id).FirstOrDefault();
                                if (newRec == null)
                                {
                                    db.TransactionBody.Remove(rec);
                                }
                                else
                                {
                                    PropertyInfo[] properties =
                                        EntityClone.GetProperties(typeof(TransactionBodyEntity));
                                    foreach (PropertyInfo property in properties)
                                    {
                                        property.SetValue(rec, property.GetValue(newRec.Body));
                                    }

                                    body.Remove(newRec);
                                }
                            }

                            // извлекаем новые записи
                            foreach (var rec in body)
                            {
                                db.TransactionBody.Add(rec.Body);
                            }

                            db.SaveChanges();
                            dbTransaction.Commit();
                            result = true;
                        }
                    }
                    catch (Exception e)
                    {
                        dbTransaction.Rollback();
                        Console.WriteLine("Нет изменений в транзакциях");
                    }
                }
            }

            return(result);
        }