Man*_*ala 5 c# sql-server asp.net-mvc linq-to-entities entity-framework
我收到类似上面标签的错误,它将位于
返回视图(st.employees.Find(id));
仅在上面的地方,任何人都可以帮我解决这个问题!我的代码是
namespace StartApp.Controllers
{
public class EmployController : Controller
{
StartEntities st = new StartEntities();
//List
public ActionResult List()
{
return View(st.employees.ToList());
}
//Details
public ActionResult Details(int id = 0)
{
return View(st.employees.Find(id));
}
//Create
public ActionResult Create()
{
return View();
}
[HttpPost,ValidateAntiForgeryToken]
public ActionResult Create(employee e)
{
using(st)
{
st.employees.Add(e);
try
{
st.SaveChanges();
}
catch
{
System.Diagnostics.Debug.WriteLine("Here is an error");
}
}
return RedirectToAction("List");
}
//edit
public ActionResult Edit(int id = 0)
{
return View(st.employees.Find(id));
}
[HttpPost,ValidateAntiForgeryToken]
public ActionResult Edit(employee e)
{
st.Entry(e).State = EntityState.Modified;
st.SaveChanges();
return RedirectToAction("List");
}
//Delete
public ActionResult Delete(int id = 0)
{
return View(st.employees.Find(id));
}
[HttpPost,ActionName("Delete")]
public ActionResult Delete_conf(int id)
{
employee emp = st.employees.Find(id);
st.employees.Remove(emp);
st.SaveChanges();
return RedirectToAction("List");
}
}
Run Code Online (Sandbox Code Playgroud)
}
任何人都可以帮助我纠正该错误!
当您的实体主键为 A 类型并且您将非 A 类型的变量传递给Find方法时,通常会发生此异常。
从方法的官方文档中Find,它可能会抛出以下异常
无效操作异常
如果键值的类型与要查找的实体类型的键值的类型不匹配,则抛出。
确保在调用该Find方法时使用相同的类型变量。
在您的代码中,您将一个整数变量传递给该Find方法。从错误中我相信您的实体类主键不是 int 类型。可能是Guid类型,在这种情况下,请确保将有效的 Guid 值传递给Find方法。
您可以打开 edmx 文件并查看密钥的类型,并确保将相同的类型传递给该Find方法。
只需右键单击 edmx 文件中的实体并选择属性。
| 归档时间: |
|
| 查看次数: |
13324 次 |
| 最近记录: |