当我尝试更新记录时,它会创建新记录而不是更新

问题描述 投票:0回答:1

我尝试在一个视图和控制器组合创建和编辑文件。我通过检查 id 来检测何时编辑和何时更新。如果 id==0 那么它将create。但当我更新时,它会始终创建,因为 id 始终为 0。但表单的填充值是正确的。这是我的代码。

这是我的

控制器:

public IActionResult Upsert(int? id) { if(id == null || id == 0) { return View(); } Product product = _productRepository.Get(u=>u.Id == id); return View(product); } [HttpPost] public IActionResult Upsert(Product product) { if (ModelState.IsValid) { if (product.Id == 0) { _productRepository.Add(product); } else { _productRepository.Update(product); } _productRepository.Save(); return RedirectToAction("Index"); } return View(); }
这是我的

产品型号

using System.ComponentModel.DataAnnotations; namespace test.Models { public class Product { public int Id { get; set; } [Required] public string? Title { get; set; } public string? Description { get; set; } [Required] public string? ISBN { get; set; } [Required] public string? Author { get; set; } [Required] [Range(1,1000)] [Display(Name ="ListPrice")] public int ListPrice { get; set; } [Required] [Range(1, 1000)] [Display(Name = "Price for 1-50")] public int Price { get; set; } [Required] [Range(1, 1000)] [Display(Name = "Price for 50+")] public int Price50 { get; set; } [Required] [Range(1, 1000)] [Display(Name = "Price for 100+")] public int Price100 { get; set; } } }
这是我的

视图

@model Product <div class="row justify-content-center"> <div class="col-10"> <div class="card shadow border-0 mt-4"> <div class="card-header bg-secondary bg-gradient m-lg-0 py3"> <div class="row"> <div class="col-12 text-center"> <h2 class="text-white py-2">Update Category</h2> </div> </div> </div> <div class="card-body p-4"> <form method="post" class="row"> <input asp-for="Id" hidden value="0" /> <div class="row"> <div class="col-10"> <div class="border pt-3"> <div class="py-2"> <input type="text" asp-for="Title" placeholder="Title" class="form-control form-floating shadow border-0" /> <span asp-validation-for="Title" class="text-danger"></span> </div> <div class="py-2"> <textarea asp-for="Description" placeholder="Discription" class="form-control form-floating shadow border-0"></textarea> </div> <div class="py-2"> <input type="text" asp-for="ISBN" placeholder="ISBN" class="form-control form-floating shadow border-0" /> <span asp-validation-for="ISBN" class="text-danger"></span> </div> <div class="py-2"> <input type="text" asp-for="Author" placeholder="Author" class="form-control form-floating shadow border-0" /> <span asp-validation-for="Author" class="text-danger"></span> </div> <div class="py-2"> <input type="number" asp-for="ListPrice" placeholder="ListPrice" class="form-control form-floating shadow border-0" /> <span asp-validation-for="ListPrice" class="text-danger"></span> </div> <div class="py-2"> <input type="text" asp-for="Price" placeholder="Price for 1-50" class="form-control form-floating shadow border-0" /> <span asp-validation-for="Price" class="text-danger"></span> </div> <div class="py-2"> <input type="text" asp-for="Price50" placeholder="Price for 50+" class="form-control form-floating shadow border-0" /> <span asp-validation-for="Price50" class="text-danger"></span> </div> <div class="py-2"> <input type="text" asp-for="Price100" placeholder="Price for 100+" class="form-control form-floating shadow border-0" /> <span asp-validation-for="Price100" class="text-danger"></span> </div> <div class="row mt-5"> <div class="col-6"> <button type="submit" class="btn btn-primary form-control">Create</button> </div> <div class="col-6"> <a asp-controller="Product" asp-action="Index" class="btn btn-outline-primary form-control">Back to List</a> </div> </div> </div> </div> </div> </form> </div> </div> </div> </div> @section Scripts{ <script> tinymce.init({ selector: 'textarea', plugins: 'ai tinycomments mentions anchor autolink charmap codesample emoticons image link lists media searchreplace table visualblocks wordcount checklist mediaembed casechange export formatpainter pageembed permanentpen footnotes advtemplate advtable advcode editimage tableofcontents mergetags powerpaste tinymcespellchecker autocorrect a11ychecker typography inlinecss', toolbar: 'undo redo | blocks fontfamily fontsize | bold italic underline strikethrough | link image media table mergetags | align lineheight | tinycomments | checklist numlist bullist indent outdent | emoticons charmap | removeformat', tinycomments_mode: 'embedded', tinycomments_author: 'Author name', mergetags_list: [ { value: 'First.Name', title: 'First Name' }, { value: 'Email', title: 'Email' }, ], ai_request: (request, respondWith) => respondWith.string(() => Promise.reject("See docs to implement AI Assistant")), }); </script> @{ <partial name="_ValidationScriptsPartial" /> } }
我使用

存储库模式作为数据库..存储库模式很好..因为创建正在工作..当我尝试处理单独的编辑和更新文件时,更新也正在工作。但我想在这里结合两者。

这里我还提供存储库... 这是我的存储库

界面 IRepository:

using System.Linq.Expressions; namespace test.dataAccess.Repository.IRepository { public interface IRepository<T> where T : class { IEnumerable<T> GetAll(); T Get(Expression<Func<T, bool>> filter); void Add(T entity); void Remove(T entity); void RemoveRange(IEnumerable<T> entity); } }
这是 

IRepository 的实现

using Microsoft.EntityFrameworkCore; using System.Linq.Expressions; using test.dataAccess.Data; using test.dataAccess.Repository.IRepository; namespace test.dataAccess.Repository { public class Repository<T> : IRepository<T> where T : class { private readonly ApplicationDbContext _db; internal DbSet<T> dbSet; public Repository(ApplicationDbContext db) { _db = db; this.dbSet = _db.Set<T>(); } public void Add(T entity) { dbSet.Add(entity); } public T Get(Expression<Func<T, bool>> filter) { IQueryable<T> query = dbSet.Where(filter); return query.FirstOrDefault(); } public IEnumerable<T> GetAll() { IQueryable<T> query = dbSet; return query.ToList(); } public void Remove(T entity) { dbSet.Remove(entity); } public void RemoveRange(IEnumerable<T> entity) { dbSet.RemoveRange(entity); } } }
这是IProductRepository的

界面

using test.Models; namespace test.dataAccess.Repository.IRepository { public interface IProductRepository : IRepository<Product> { void Update(Product product); void Save(); } }
这是我的存储库

接口IRepository

using System.Linq.Expressions; namespace test.dataAccess.Repository.IRepository { public interface IRepository<T> where T : class { IEnumerable<T> GetAll(); T Get(Expression<Func<T, bool>> filter); void Add(T entity); void Remove(T entity); void RemoveRange(IEnumerable<T> entity); } }
以及

IProductRepository的实现:

using test.dataAccess.Data; using test.dataAccess.Repository.IRepository; using test.Models; namespace test.dataAccess.Repository { public class ProductRepository : Repository<Product>, IProductRepository { private readonly ApplicationDbContext _db; public ProductRepository(ApplicationDbContext db) : base(db) { _db = db; } public void Save() { _db.SaveChanges(); } public void Update(Product product) { _db.Update(product); } } }
我正在尝试

结合编辑和创建页面。 **创建正在工作**但是当我尝试更新数据时,它将创建而不是update。当我调试时,我发现当调用 post 方法时,id 值始终为 zero 。所以它将创建而不是更新

c# asp.net-mvc entity-framework asp.net-core entity-framework-core
1个回答
0
投票
public void Update(Product product) { _db.Entry(product).State = EntityState.Modified; }
您可能还需要将产品附加到上下文中以便对其进行跟踪。因此,在需要时,在更改状态之前使用此行

_db.Attach(product);
    
© www.soinside.com 2019 - 2024. All rights reserved.