CRUD операция типа Upsert
изучаю курс [Udemy] ASP.NET Core MVC для .NET 5. дошёл до 54 урока и не могу продвинуться дальше. Суть проблемы: Вместо стандартного Create и Edit задумано сделать Upsert, но при создании вываливается ошибка, которую никак не могу победить, даже заменяя свой код исходниками Вот модель :
public class Product
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
public string Description { get; set; }
[Range(1, int.MaxValue)]
public double Price { get; set; }
public string Image { get; set; }
[Display(Name = "Category Type")]
public int CategoryId { get; set; }
[ForeignKey("CategoryId")]
public virtual Category Category { get; set; }
}
}
ViewModel :
public class ProductVM
{
public Product Product { get; set; }
public IEnumerable<SelectListItem> CategorySelectList { get; set; }
}
Controller: GET-Upsert
public IActionResult Upsert(int? id)
{
ProductVM productVM = new()
{
Product = new Product(),
CategorySelectList = _db.Category.Select(i => new SelectListItem
{
Text = i.Name,
Value = i.Id.ToString()
})
};
if (id == null)
{
return View(productVM);
}
else
{
productVM.Product = _db.Product.Find(id);
if (productVM.Product == null)
{
return NotFound();
}
return View(productVM);
}
}
Controller: POST-Upsert
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Upsert(ProductVM productVM)
{
if (ModelState.IsValid)
{
var files = HttpContext.Request.Form.Files;
string webRootPath = _webHostEnvironment.WebRootPath;
if (productVM.Product.Id == 0)
{
//Creating
string upload = webRootPath + WC.ImagePath;
string fileName = Guid.NewGuid().ToString();
string extension = Path.GetExtension(files[0].FileName);
using (var fileStream = new FileStream(Path.Combine(upload, fileName + extension), FileMode.Create))
{
files[0].CopyTo(fileStream);
}
productVM.Product.Image = fileName + extension;
_db.Product.Add(productVM.Product);
}
else
{
//updating
}
_db.SaveChanges();
return RedirectToAction("Index");
}
return View();
}
Источник: Stack Overflow на русском