这个操作中,参数类型 'Edm.String' 和 'Edm.Int32' 不兼容。

6

我遇到了以上所示的错误标签,将会代替

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

}

能有人帮忙纠正这个错误吗!


看一下 Employee 实体。它的 Key 的类型是什么? - Reza Aghaei
它只是主键。 - Manoj Kumar Miriyala
你的类中key的数据类型是什么?(查看edmx或代码文件中字段的属性) - Reza Aghaei
3个回答

7
当您的实体主键是类型A,但您传递给“Find”方法的变量不是类型A时,通常会发生此异常。
从“Find”方法的官方文档中,它可能会抛出以下异常:
InvalidOperationException
如果键值的类型与要查找的实体类型的键值的类型不匹配,则会抛出该异常。
确保在调用“Find”方法时使用相同类型的变量。
在您的代码中,您正在将整数变量传递给“Find”方法。根据错误信息,我认为您的实体类主键不是int类型。也许它是Guid类型,在这种情况下,请确保向“Find”方法传递有效的Guid值。
您可以打开edmx文件并查看您的键的类型,以确保将相同类型传递给“Find”方法。

只需在edmx文件中右键单击实体,然后选择属性。

enter image description here


谢谢您的建议,我是MVC的新手。请问什么是A类型? - Manoj Kumar Miriyala
它可以是任何类型(例如:Guid)。在您的代码中,您正在传递一个int变量。检查edmx文件中的实体类以查看它是什么类型。 - Shyju
是的,我没有将它声明为int。我将其声明为varchar(50)。现在,我应该传递什么值而不是0呢? - Manoj Kumar Miriyala

1

看起来你正在遵循MVC模式。

我也遇到了这个错误,原因是我将id参数作为整数传递,而在我的模型中声明为"字符串"。

示例:

public class Object
{
    public string id { get; set; }
    public string property1{ get; set; }
    public string property2{ get; set; }
    public string property3{ get; set; }
}

0

Find() 只接受与你要使用 Find() 的表的主键数据类型相似的参数。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接