C# 更新实体时,序列不包含任何元素
我想更新我的产品实体,但每当我提交表单时,它就会抛出: System.InvalidOperationException:“序列不包含元素” 我的看法是:C# 更新实体时,序列不包含任何元素,c#,asp.net-mvc,C#,Asp.net Mvc,我想更新我的产品实体,但每当我提交表单时,它就会抛出: System.InvalidOperationException:“序列不包含元素” 我的看法是: @model myadminpanel.Models.product @using (Html.BeginForm()) { <div class="container"> <div class="form-group"> <label>ProductName
@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>
}
这是我的产品模型:
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; }
}
}
名称空间myadminpanel.Models
{
使用制度;
使用System.Collections.Generic;
公共部分类积
{
public int ProductID{get;set;}
公共字符串ProductName{get;set;}
公共字符串ProductDescription{get;set;}
公共可空价格{get;set;}
公共可空数量{get;set;}
公共字符串CategoryName{get;set;}
公共可空类别ID{get;set;}
公共虚拟类别{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">
...
@使用(Html.BeginForm())
{
@Html.HiddenFor(model=>model.ProductID)
...
db.products.Where(x=>x.ProductID==id)
不返回任何元素,然后First()导致“Sequence contains no elements”
@using (Html.BeginForm())
{
@Html.HiddenFor(model => model.ProductID)
<div class="container">
...