Example #1
0
        public async Task <ActionResult <Author> > PostAuthor(AddAuthorDTO author)
        {
            string[] writers = author.WriterName.Split(',');
            var      book    = new Book()
            {
                ISBN = author.ISBN
            };

            _context.Attach(book);
            foreach (var w in writers)
            {
                var writer = new Writer()
                {
                    WriterName = w.Trim()
                };
                _context.Attach(writer);
                var newAuthor = new Author {
                    Book = book, Writer = writer
                };
                _context.Author.Add(newAuthor);
            }

            await _context.SaveChangesAsync();

            return(NoContent());
        }
        public Book Post([FromForm] AddBookDTO book)
        {
            var publisher = new Publisher {
                PublisherName = book.PublisherName
            };

            _context.Attach(publisher);
            var category = new Category {
                CategoryID = book.CategoryID
            };

            _context.Attach(category);
            string Img = _imageService.SaveImg(book.Image);


            var newBook = new Book
            {
                BookImgUrl      = Img,
                ISBN            = book.ISBN,
                Title           = book.Title,
                Category        = category,
                Publisher       = publisher,
                PublicationDate = book.PublicationDate,
                Edition         = book.Edition,
                Pagination      = book.Pagination,
                Price           = book.Price,
                Plot            = book.Plot,
            };

            return(newBook);
        }
        public async Task Delete(int id)
        {
            T item = await Get(id);

            _db.Attach(item).State = EntityState.Deleted;
            await _db.SaveChangesAsync();
        }
Example #4
0
        /// <summary>
        /// POST action, process data from form and saves changes
        /// </summary>
        /// <returns></returns>
        public async Task <IActionResult> OnPostAsync()
        {
            // check valid state
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            // mark objects to update
            _context.Attach(Company).State         = EntityState.Modified;
            _context.Attach(Company.Address).State = EntityState.Modified;

            try
            {
                // save changes
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!CompanyExists(Company.ID))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            TempData[EFlashMessage.Success] = "Uloženo";

            return(RedirectToPage("./Index"));
        }
Example #5
0
        public async Task <IRepositoryResponse> Add(TEntity entity)
        {
            if (entity == null)
            {
                throw new ArgumentNullException(nameof(entity));
            }

            var result = new RepositoryResponse();

            if (entity.Id != 0)
            {
                result.Success = false;

                return(result);
            }

            try
            {
                if (await context.Roles.AnyAsync(r => r.RoleLevel == entity.RoleLevel))
                {
                    result.Success = false;

                    return(result);
                }

                context.Attach(entity);

                foreach (var entry in context.ChangeTracker.Entries())
                {
                    var dbEntry = (IEntityBase)entry.Entity;

                    if (dbEntry is UserApp)
                    {
                        entry.State = EntityState.Modified;
                    }
                    else if (dbEntry is UserRole)
                    {
                        entry.State = EntityState.Modified;
                    }
                    else
                    {
                        // Otherwise do nothing...
                    }
                }

                await context.SaveChangesAsync();

                result.Success = true;
                result.Object  = entity;

                return(result);
            }
            catch (Exception exp)
            {
                result.Success   = false;
                result.Exception = exp;

                return(result);
            }
        }
Example #6
0
        public async Task <Advertisement> CreateAsync(Advertisement advertisement)
        {
            Context.Attach(advertisement.User);
            Context.Advertisements.Add(advertisement);
            Context.Details.AddRange(advertisement.Details);
            await Context.SaveChangesAsync();

            return(advertisement);
        }
Example #7
0
        /// <summary>
        /// POST action. Process user edit form
        /// </summary>
        /// <returns>If process is without error, returns user detail, else returns current page with error</returns>
        public async Task <IActionResult> OnPostAsync()
        {
            // check if model is valid
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            var appUser = new AppUser();

            // map userEdit back to AppUser
            appUser = this.mapper.Map <AppUser>(UserEdit);


            // check if username is not used
            if (!VerifyUsername(appUser.UserName, appUser.Id))
            {
                TempData[EFlashMessage.Error] = "Uživatelské jméno je již použito";

                return(Page());
            }

            // mark objects for update
            _context.Attach(appUser).State         = EntityState.Modified;
            _context.Attach(appUser.Address).State = EntityState.Modified;

            // exclude role and password property from update
            // user can not update own role
            // for change password exists different form
            _context.Entry(appUser).Property(x => x.Password).IsModified = false;
            _context.Entry(appUser).Reference(x => x.Role).IsModified    = false;


            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!AppUserExists(appUser.Id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            TempData[EFlashMessage.Success] = "Uloženo";

            return(RedirectToPage("/User/Details"));
        }
Example #8
0
        public Pet CreatePet(Pet createdPet)
        {
            if (createdPet.Hero != null)
            {
                _context.Attach(createdPet.Hero).State = EntityState.Unchanged;
            }

            var savedPet = _context.Add(createdPet).Entity;

            createdPet.Hero.Pets.Add(savedPet);
            _context.SaveChanges();
            return(savedPet);
        }
Example #9
0
 /// <summary>
 /// Update user's refresh token async
 /// </summary>
 /// <param name="user">User</param>
 /// <param name="refreshToken">New refresh token</param>
 /// <returns>Task</returns>
 public async Task UpdateUserRefreshTokenAsync(User user, RefreshToken refreshToken)
 {
     _dbContext.Attach(user);
     user.RefreshToken = refreshToken;
     _dbContext.Users.Update(user);
     await _dbContext.SaveChangesAsync();
 }
Example #10
0
        public async Task <ActionResult <Borrow> > PostBorrow(AddBorrowDto borrow)
        {
            var user = User.Claims.FirstOrDefault(c => c.Type == "Id")?.Value;

            if (user == null)
            {
                return(Unauthorized());
            }

            var type = (TypeEnum)TypeEnum.Parse(typeof(TypeEnum), User.Claims.FirstOrDefault(c => c.Type == "Type").Value);
            var rule = await _context.Rule.FirstOrDefaultAsync(r => r.Type == type);

            var amount = rule.BookAmount;
            var count  = _context.Borrow.Count(b => b.User.PID == user && (b.Status == TypeEnum.Borrowing || b.Status == TypeEnum.Wait));


            if (amount > count)
            {
                var newUser = new User()
                {
                    PID = user
                };
                _context.Attach(newUser);

                var book = new Book()
                {
                    BookID = borrow.Book
                };
                _context.Attach(book);



                var newBorrow = new Borrow()
                {
                    User   = newUser,
                    Book   = book,
                    Status = TypeEnum.Wait,
                };
                _context.Borrow.Add(newBorrow);


                await _context.SaveChangesAsync();


                return(CreatedAtAction("GetBorrow", new { id = newBorrow.BorrowId }, borrow));
            }
            return(BadRequest("Book Limited"));
        }
Example #11
0
        public async Task <Message> Create(Message item)
        {
            try
            {
                _db.Attach(item.Group);
                _db.Attach(item.Sender);
            }
            catch (InvalidOperationException ex)
            {
            }
            var created = await _db.Messages.AddAsync(item);

            await _db.SaveChangesAsync();

            return(created.Entity);
        }
Example #12
0
        // To protect from overposting attacks, enable the specific properties you want to bind to.
        // For more details, see https://aka.ms/RazorPagesCRUD.
        public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            _context.Attach(Serie).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!SerieExists(Serie.Id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(RedirectToPage("./Index"));
        }
Example #13
0
        public void UpdateBakery(int id, Bakery bakery)
        {
            Bakery bakeryFinded = _context.Bakery.Single(b => b.id == id);

            if (bakeryFinded != null)
            {
                _context.Attach(bakeryFinded);

                bakery.location = new Point(bakery.longitude, bakery.latitude)
                {
                    SRID = 4326
                };

                bakeryFinded.name      = bakery.name;
                bakeryFinded.details   = bakery.details;
                bakeryFinded.openHour  = bakery.openHour;
                bakeryFinded.closeHour = bakery.closeHour;
                bakeryFinded.latitude  = bakery.latitude;
                bakeryFinded.longitude = bakery.longitude;
                bakeryFinded.location  = bakery.location;

                _context.Bakery.Update(bakeryFinded);
                _context.SaveChanges();
            }
        }
Example #14
0
        public void Update(Image image)
        {
            var dbImage = MappingHelper.Map(image);

            _databaseContext.Attach(dbImage);
            _databaseContext.SaveChanges();
        }
 public override int Insert(WorkoutSessionExercise entity)
 {
     DatabaseContext.Attach(entity.Exercise);
     DatabaseContext.AttachOwnable(entity.WorkoutSession);
     DatabaseContext.InsertOwnable(entity);
     return(DatabaseContext.SaveChanges());
 }
        public async Task <StudentLearningEventLog> AddorUpdateAsync(StudentLearningEventLog model)
        {
            var id = _db.StudentLearningEventLogs
                     .Where(el =>
                            el.StudentElectronicMailAddress == model.StudentElectronicMailAddress &&
                            el.LeaningAppUrl == model.LeaningAppUrl &&
                            el.UTCStartDate == model.UTCStartDate
                            )
                     .Select(el => el.Id)
                     .FirstOrDefault();

            if (id != 0)
            {
                model.Id = id;
                _db.Attach(model);
                _db.Entry(model).State = EntityState.Modified;
            }
            else
            {
                _db.Add(model);
            }
            await _db.SaveChangesAsync();

            return(model);
        }
Example #17
0
        private void WebRequestDirSaver(MResponse ClientResponse, MNetworkClient NetworkClient)
        {
            if (!AccessController.IsPrivilege(NetworkClient, "requests.add"))
            {
                return;
            }

            var WebRequestDirItem = Package.Unpacking <WebRequestDir>(ClientResponse.DataBytes);

            using (var db = new DatabaseContext())
            {
                db.Attach(WebRequestDirItem);
                db.SaveChanges();

                Sender.Broadcast("WebRequestDir.Save.Confirm", WebRequestDirItem, ClientResponse.WindowUid);

                WebRequestItem WebRequestItem =
                    db.WebRequestItems.FirstOrDefault(x => x.Id == WebRequestDirItem.WebRequestItemId);

                MBinding_WebRequest MBinding = new MBinding_WebRequest();
                MBinding.Item      = WebRequestItem;
                MBinding.Params    = db.WebRequestParamsItems.Where(x => x.WebRequestItemId == WebRequestItem.Id).ToArray();
                MBinding.Directory = WebRequestDirItem;

                Sender.Broadcast("WebRequestItem.MBinding_WebRequest.Add", MBinding);
            }
        }
Example #18
0
 public void Delete(User entity)
 {
     if (_db.Entry(entity).State == EntityState.Detached)
     {
         _db.Attach(entity);
     }
     _db.Users.Remove(entity);
 }
Example #19
0
 public void Delete(GameDiscount entity)
 {
     if (_db.Entry(entity).State == EntityState.Detached)
     {
         _db.Attach(entity);
     }
     _db.GameDiscounts.Remove(entity);
 }
Example #20
0
 public void Delete(Genre entity)
 {
     if (_db.Entry(entity).State == EntityState.Detached)
     {
         _db.Attach(entity);
     }
     _db.Genres.Remove(entity);
 }
 public void Delete(DollarPrice entity)
 {
     if (_db.Entry(entity).State == EntityState.Detached)
     {
         _db.Attach(entity);
     }
     _db.DollarPrice.Remove(entity);
 }
Example #22
0
 public new async Task <int> Update(Article article)
 {
     await using var context = new DatabaseContext();
     //context.Entry(await context.Articles.FirstOrDefaultAsync(x=> x.Id==article.Id)).CurrentValues.SetValues(article);
     context.Attach(article);
     context.Entry(article).State = EntityState.Modified;
     return(await context.SaveChangesAsync());
 }
 public void Delete(Platform entity)
 {
     if (_db.Entry(entity).State == EntityState.Detached)
     {
         _db.Attach(entity);
     }
     _db.Platforms.Remove(entity);
 }
Example #24
0
 public void Delete(GameEdition entity)
 {
     if (_db.Entry(entity).State == EntityState.Detached)
     {
         _db.Attach(entity);
     }
     _db.GameEditions.Remove(entity);
 }
 public void Delete(Comment entity)
 {
     if (_db.Entry(entity).State == EntityState.Detached)
     {
         _db.Attach(entity);
     }
     _db.Comments.Remove(entity);
 }
        public async Task <bool> UpdateAsync(Employee employee)
        {
            try
            {
                _dbcontext.Attach(employee);
                _dbcontext.Entry(employee).State = EntityState.Modified;
                await _dbcontext.SaveChangesAsync();

                //_dbcontext.Update(employee);
                //await _dbcontext.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException dex)
            {
                foreach (var entry in dex.Entries)
                {
                    if (entry.Entity is Employee)
                    {
                        var proposedValues = entry.CurrentValues;
                        var databaseValues = entry.GetDatabaseValues();

                        /*foreach (var property in proposedValues.Properties)
                         * {
                         *  var proposedValue = proposedValues[property];
                         *  var databaseValue = databaseValues[property];
                         *
                         *  proposedValues[property] = proposedValue;
                         * }*/

                        // Refresh original values to bypass next concurrency check
                        entry.OriginalValues.SetValues(databaseValues);
                        try
                        {
                            await _dbcontext.SaveChangesAsync();

                            return(true);
                        }
                        catch
                        {
                            return(false);
                        }
                    }
                    else
                    {
                        /*throw new NotSupportedException(
                         *  "Don't know how to handle concurrency conflicts for "
                         + entry.Metadata.Name);*/
                        return(false);
                    }
                }
            }
            return(true);
        }
Example #27
0
        public IActionResult Delete(int Id)
        {
            var product = new Product()
            {
                Id = Id
            };

            _databaseContext.Attach(product);
            _databaseContext.Remove(product);
            _databaseContext.SaveChanges();

            return(Ok());
        }
Example #28
0
        /// <summary>
        /// POST action. Proccess edit form
        /// </summary>
        /// <returns>If process is without error return index page, else return current page with errors</returns>
        public async Task <IActionResult> OnPostAsync()
        {
            // check model
            if (!ModelState.IsValid)
            {
                // loads invoice from database
                Invoice = await _context.Invoice
                          .Include(i => i.InvoiceItems)
                          .Include(i => i.BillToCompany)
                          .Include(i => i.Suppliercompany)
                          .FirstOrDefaultAsync(m => m.ID == Invoice.ID);

                LoadCompanyList();

                return(Page());
            }

            // load selected companies from selects and assign them to invoice
            Invoice.Suppliercompany = await _context.Company.FindAsync(SelectSupplierCompany);

            Invoice.BillToCompany = await _context.Company.FindAsync(SelectBillCompany);

            // mark changes
            _context.Attach(Invoice).State = EntityState.Modified;

            try
            {
                // loads old items
                var items = _context.InvoiceItem.Where(i => i.Invoice.ID == Invoice.ID);

                // remove them from invoice
                _context.InvoiceItem.RemoveRange(items);

                // save changes (EF adds items for us)
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!InvoiceExists(Invoice.ID))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(RedirectToPage("./Index"));
        }
Example #29
0
        public async Task <Customer> Update(Customer customer)
        {
            try
            {
                _db.Attach(customer);
                _db.Entry(customer).State = EntityState.Modified;
                await _db.SaveChangesAsync();
            }
            catch (Exception e)
            {
            }

            return(customer);
        }
Example #30
0
 public void Add(TInterface item)
 {
     try
     {
         var newitem = Mapping.Mapper.Map <TEntity>(item);
         dbContext.Attach(newitem);
         dbContext.Entry(newitem).State = EntityState.Added;
         dbContext.SaveChanges();
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }