【发布时间】:2021-01-20 13:21:53
【问题描述】:
我正在制作一个 CRUD 应用程序,我正在尝试通过视图编辑对象的单个实例并将更改保存到数据库中。我将实体框架与存储库模式一起使用。我遇到的问题是我的对象的主键是字符串而不是 int。
因此,我在编辑客户时尝试访问的路径 URL 如下所示: /devices/editSingle/wefs3-amr3x-ngte3
我正在对另一个具有 int 作为 Id 且工作正常的对象使用完全相同的代码。但是,我很难重构此代码,因此它使用字符串作为主键。当我运行此代码时,当我单击editSingle for a customer 按钮时,它运行没有问题,我进入NotFound() 页面。所以我认为我的GetByBranchId 方法有问题
客户模型
[Key]
[JsonProperty("id")]
public string BranchId { get; set; }
[JsonProperty("name")]
public string CustomerName { get; set; }
控制器
private readonly DbContext _dbContext;
private readonly ICustomersRepository _customersRepository;
public CustomersController(DbContext dbContext, ICustomersRepository customersRepository)
{
_dbContext = dbContext;
_customersRepository = customersRepository;
}
public async Task<IActionResult> EditSingle(string branchId)
{
if (branchId == null)
{
return NotFound();
}
var customers = await _customersRepository.GetByBranchId(branchId);
if (customers == null)
{
return NotFound();
}
return View(customers);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> EditSingle(string branchid, Customers customers)
{
if (branchid != customers.BranchId)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
// Here all the fields that should get updated can be stated
_dbContext.Entry(customers).Property(p => p.CustomerName).IsModified = true;
await _dbContext.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!CustomerExists(customers.BranchId))
{
return NotFound();
}
else
{
throw;
}
}
}
return View(customers);
}
private bool CustomerExists(string branchid)
{
return _dbContext.Customers.Any(e => e.BranchId == branchid);
}
在查找 int 的 ID 时,此方法运行良好。在寻找 string 时,它似乎无法正常运行
存储库
public async Task<Customers> GetByBranchId(string branchId)
{
return await _dbContext.Set<Customers>().FindAsync(branchId);
}
编辑
我设法修复了它,在我看来这是个问题,我没有在我的asp-route 中指定正确的属性
旧的
<td><a asp-action="EditSingle" asp-route-Id="@customer.BranchId">Edit</a></td>
修复
<td><a asp-action="EditSingle" asp-route-branchId="@customer.BranchId">Edit</a></td>
【问题讨论】:
标签: c# asp.net entity-framework asp.net-core .net-core