Действие редактирования ничего не делает в автомаппере - PullRequest
0 голосов
/ 13 июля 2020

Я использую Visual Studio 2019, net core 3.1 и automapper. Мое действие редактирования не редактирует запись. Я видел обучающие программы, но все они посвящены одному действию, и мне нужно сделать грубую работу. Взяв в качестве примера обычное действие редактирования, я сделал это:

public class CustomerCountriesController : Controller
    {
        private readonly ApplicationDbContext _context;
        private readonly IMapper _mapper;

        public CustomerCountriesController(ApplicationDbContext context, IMapper mapper)
        {
            _context = context;
            _mapper = mapper;
        }

        // GET: CustomerCountries
        public async Task<IActionResult> Index()        
        {
            //CustomerCountries customerCountry = new CustomerCountries();
            var customerCountry = await _context.CustomerCountries.ToListAsync();            
            List<CustomerCountriesDto> countries = _mapper.Map<List<CustomerCountries>, 
                                                    List<CustomerCountriesDto>>(await _context.CustomerCountries.ToListAsync());
         
            return View(countries);
        }

public async Task<IActionResult> Edit(string id)
        {
            if (id == null)
            {
                return NotFound();
            }
            
            var customerCountries = await _context.CustomerCountries.FindAsync(id);
            var model = _mapper.Map<CustomerCountries, CustomerCountriesDto>(customerCountries);

            if (customerCountries == null)
            {
                return NotFound();
            }

            

            return View(model);
            //return View(customerCountries);
        }

        // POST: CustomerCountries/Edit/5
        // To protect from overposting attacks, enable the specific properties you want to bind to, for 
        // more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]        
        //public async Task<IActionResult> Edit(string id, [Bind("CustomerCountry")] CustomerCountries customerCountries)
        public async Task<IActionResult> Edit(string customerCountry, CustomerCountriesDto customerCountriesDto)
        {
            if (customerCountry != customerCountriesDto.CustomerCountry)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    var CustomerCountries = _mapper.Map<CustomerCountriesDto, CustomerCountries>(customerCountriesDto);                    
                    _context.Update(CustomerCountries);
                    await _context.SaveChangesAsync();                    
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!CustomerCountriesExists(customerCountriesDto.CustomerCountry))                    
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            return View(customerCountriesDto);
        }


public class AutoMapping : Profile
    {
        public AutoMapping()
        {
            CreateMap<CustomerCountries, CustomerCountriesDto>();
            CreateMap<CustomerCountriesDto, CustomerCountries>();
        }
    }

public class CustomerCountries
    {
        [StringLength(50, ErrorMessage = "Longitud máxima para el país: 50")]
        public string CustomerCountry { get; set; }

        public ICollection<CustomerRegions> CustomerRegions { get; set; }
    }

public class CustomerCountriesDto
    {
        public string CustomerCountry { get; set; }
    }

При запуске

services.AddAutoMapper(typeof(Startup));

Идентификатор таблицы - CustomerCounty

Вы можете мне сказать правильный путь? Не говорите мне читать, дайте код, чтобы я мог заставить его работать.

1 Ответ

0 голосов
/ 16 июля 2020

Я нашел решение благодаря опытному разработчику, который помог мне решить проблему и время от времени исправлял мой код (на самом деле, ребята, это действительно очень помогает). Оказалось, что я использовал поле в качестве PK: CustomerCountry ... Я не использовал и Id, когда я изменил модель, произошло обновление

var CustomerCountries = _mapper.Map<CustomerCountriesDto, CustomerCountries>(customerCountriesDto);
var country = _context.CustomerCountries.FirstOrDefault(c => c.Id == CustomerCountries.Id);
country.CustomerCountry = customerCountriesDto.CustomerCountry;
                        _context.Update(country);
                    await _context.SaveChangesAsync();  
...