【问题标题】:How to edit a single object CRUD using a string as primary key如何使用字符串作为主键编辑单个对象 CRUD
【发布时间】: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


    【解决方案1】:

    试试这个代码:

    Customers existCustomer=null;
    try
            {
              
     existCustomer= await _dbContext.Set<Customers>()
                                        .Where( i=> i.branchId==branchId)
                                         .FirstOrDefaultAsync();
             if(existCustomer==null) ....return error
               existCustomer.CustomerName = customers.CustomerName;
                _dbContext.Entry(existCustomer).Property(p => p.CustomerName).IsModified =true;
                await _dbContext.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
               if(existCustomer==null)
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }
    

    【讨论】:

    • 您好,感谢您的回答,我已经设法解决了这个问题。我的 asp-route 有问题。我不确定如何结束我的问题
    【解决方案2】:

    我相信您的问题与:How to use String property as primary key in Entity Framework.

    主键是string 而不是int 的类似情况。我还假设函数 GetByBranchId 由于同样的原因也不起作用(使用 string 搜索 int)。

    编辑:您可能会发现单独保留主键(将其保留为 自动递增 int)并将分支 id 存储在其自己的索引中更有用。

    如果这有帮助,请告诉我,谢谢。

    【讨论】:

    • 嘿,谢谢您的回答,主键是字符串没有问题,它不应该自动递增,因为我是从外部 API 中提取这些信息的。我遇到的问题是如何使用 GetBranchId 通过字符串查找客户
    • @Bram 在这种情况下,您可以使用类似_dbContext.Set&lt;Customers&gt;().SingleOrDefault(e =&gt; e.branchId == branchId);
    • @Bram _dbContext.Set&lt;Customers&gt;().SingleOrDefaultAsync(e =&gt; e.branchId == branchId);
    • 非常感谢,感谢您的评论,我设法解决了这个问题。另外我忘记将我的 asp-route 更改为 branchId 而不是 Id。
    猜你喜欢
    • 2018-05-09
    • 2021-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多