gpt4 book ai didi

c# - 更新实体时序列不包含任何元素

转载 作者:行者123 更新时间:2023-11-30 22:55:13 25 4
gpt4 key购买 nike

我想更新我的产品实体,但每当我提交表单时,它都会抛出:

System.InvalidOperationException: 'Sequence contains no elements'

这是我的观点:

@model myadminpanel.Models.product
@using (Html.BeginForm())
{
<div class="container">
<div class="form-group">
<label>ProductName</label>
@Html.TextBoxFor(x => x.ProductName, new { @class = "form-control" });
</div>
<div class="form-group">
<label>ProductDescription</label>
@Html.TextBoxFor(x => x.ProductDescription, new { @class = "form-control" });
</div>
<div class="form-group">
<label>Price</label>
@Html.TextBoxFor(x => x.Price, new { @class = "form-control" });
</div>
<div class="form-group">

<label>Quantity</label>
@Html.TextBoxFor(x => x.Quantity, new { @class = "form-control" });

<div class="button">
<button>Submit</button>
</div>
</div>
}

我的 Controller 编辑代码是这样的:

public ActionResult ProductEdit(int id)
{
var item = db.products.Where(x => x.ProductID == id).First();

return View(item);


}
[HttpPost]
public ActionResult ProductEdit(product model)
{
var item = db.products.Where(x => x.ProductID == model.ProductID).First();
item.ProductName= model.ProductName;
item.ProductDescription = model.ProductDescription;
item.Price = model.Price;
item.Quantity = model.Quantity;

db.SaveChanges();
return View();
}

这是我的产品模型:

namespace myadminpanel.Models
{
using System;
using System.Collections.Generic;

public partial class product
{
public int ProductID { get; set; }
public string ProductName { get; set; }
public string ProductDescription { get; set; }
public Nullable<decimal> Price { get; set; }
public Nullable<int> Quantity { get; set; }
public string CategoryName { get; set; }
public Nullable<int> CategoryID { get; set; }

public virtual category category { get; set; }
}
}

最佳答案

您的表单不包含您正在修改的实体的 id,所以这

var item = db.products.Where(x => x.ProductID == id).First();

运行为

var item = db.products.Where(x => x.ProductID == 0).First();

并且没有 ID = 0 的任何产品,因此 First 找不到第一个匹配项(因为没有任何可匹配的对象)。

因此,将 ID 添加为隐藏字段:

@using (Html.BeginForm())
{
@Html.HiddenFor(model => model.ProductID)

<div class="container">
...

关于c# - 更新实体时序列不包含任何元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55441299/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com