c# - 参数类型 'Edm.String' 和 'Edm.Int32' 与此操作不兼容

标签 c# sql-server asp.net-mvc entity-framework linq-to-entities

我收到类似上面标签的错误,该错误将位于

的位置

return View(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");
    }

}

谁能帮我改正这个错误!

最佳答案

当您的实体主键是类型 A 而您将一个不是类型 A 的变量传递给 Find 方法时,通常会发生此异常。

来自official documentation Find 方法,可能会抛出以下异常

InvalidOperationException

Thrown if the types of the key values do not match the types of the key values for the entity type to be found.

确保在调用 Find 方法时使用相同类型的变量。

在您的代码中,您将整数变量传递给 Find 方法。从错误我相信你的实体类主键不是 int 类型。可能是 Guid 类型,在这种情况下,请确保将有效的 Guid 值传递给 Find 方法。

您可以打开 edmx 文件并查看 key 的类型,并确保将相同的类型传递给 Find 方法。

只需右键单击您的 edmx 文件中的实体并选择属性。

enter image description here

关于c# - 参数类型 'Edm.String' 和 'Edm.Int32' 与此操作不兼容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38832906/

相关文章:

asp.net-mvc - 处理 .NET MVC 2 Action Filters 时的执行顺序是什么?

c# - Razor 中枚举下拉列表的显示名称

c# - 在 asp.net 中读取隐藏的控件值

c# - 未更改的值和自动实现的属性

c# - SqlDataReader HasRows=True 但没有数据

sql-server - 在 sql server 中将 xml 列值编码为 xml

c# - 将 URL 参数存储为字符串变量 ASP.NET

c# - 检测重复记录,只选择第一个并用 LINQ/C# 计数

c# - 我应该如何将 lambda 表达式转换为代码(文本)?

sql-server - 更改查询的比较值时,执行时间非常令人绝望