Обновление данных в бд ASP.NET Core / EF - C#

Узнай цену своей работы

Формулировка задачи:

Предположим, что у меня есть контрол
PurseController
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using VendingMachine.Models;
using VendingMachine.Utylity;
using VendingMachine.ViewModel;
 
namespace VendingMachine.Controllers
{
    public class PurseController : Controller
    {
        VendingMachineViewModel _vm;
        IMonetaryOperations _monetaryOperations;
        VendingMachineContext _db;
 
        public PurseController(VendingMachineContext context, IMonetaryOperations monetaryOperations)
        {
            _monetaryOperations = monetaryOperations;
            _db = context;
        }
 
        protected async Task GetVM()
        {
            IQueryable<Purse> purse = _db.PurseSet.Include(p => p.Money);
            IQueryable<Product> product = _db.ProductSet;
 
            _vm = new VendingMachineViewModel();
 
            _vm.Products = await product.AsNoTracking().ToListAsync();
            _vm.Purses = await purse.AsNoTracking().ToListAsync();
        }
 
        public async Task<IActionResult> Index()
        {
            await GetVM();
 
            return View(_vm.Purses);
        }
 
        [HttpPost]
        public async Task<IActionResult> GetPay(int?[] quantity)
        {
            if (!quantity.All(q => q == null))
            {
                await GetVM();
 
                var userMoney = _vm.Purses.Where(p => p.Id == 2)
                    .FirstOrDefault()
                    .Money;
 
                _monetaryOperations.Money = userMoney.ToList();
                _monetaryOperations
                    .SetMoneyList(quantity.Select((q, i) =>
                    new Money
                    {
                        Denomination = i == 2 ? 5 : i == 3 ? 10 : i + 1,
                        Quantity = q != null ? (int)q : 0
                    }), true);

                userMoney = _monetaryOperations.Money;
 
                _db.MoneySet.UpdateRange(userMoney);
                await _db.SaveChangesAsync();
                return RedirectToAction("Index");
 
            }
 
            return NotFound();
        }
    }
}
В нем, я достаю кошелек и деньги, коряво, не в конструкторе, но достаю во вьюмодел xD
IQueryable<Purse> purse = _db.PurseSet.Include(p => p.Money);
// ----
_vm.Products = await product.AsNoTracking().ToListAsync();
Затем через метод GetPay хочу добавить денежег в свой кошелек, в данном случае пошелек получаю так

.Where(p => p.Id == 2).FirstOrDefault()

, но не в этом суть.

int?[] quantity

возвращает мне 4 значения, где 0й индекс это 1руб, 1 - 2 руб, 2 - 5 руб, 3 - 10 руб. А точнее их количество. Кладу в свой кошелек денежки, SetMoneyList и хочу произвести обновления в БД, но как это сделать?
_db.MoneySet.UpdateRange(userMoney);
Ругается на меня...
nvalidOperationException: The instance of entity type 'Money' cannot be tracked because another instance of this type with the same key is already being tracked. When adding new entities, for most key types a unique temporary key value will be created if no key is set (i.e. if the key property is assigned the default value for its type). If you are explicitly setting key values for new entities, ensure they do not collide with existing entities or temporary values generated for other new entities. When attaching existing entities, ensure that only one entity instance with a given key value is attached to the context.
Но как убрать эти самые значения Кличей, если в любом случае, если даже я и не дам значение ключам, у ключей будет значение, и это 0... Что не так?

Решение задачи: «Обновление данных в бд ASP.NET Core / EF»

textual
Листинг программы
        [HttpPost]
        public async Task<IActionResult> GetPay(int?[] quantity)
        {
            if (!quantity.All(q => q == null))
            {
                IEnumerable<Money> purse = (await _db.PurseSet.Include(p => p.Money).AsNoTracking().ToListAsync())
                    .SelectMany(p => p.Money)
                    .Where(p => p.PurseId == 2);
 
                purse.ToList().ForEach(m=>m.Quantity = 10);
 
                _db.MoneySet.UpdateRange(purse);
                await _db.SaveChangesAsync();
                return RedirectToAction("Index");
            }
 
            return NotFound();
        }

Оцени полезность:

8   голосов , оценка 4.25 из 5
Похожие ответы