【问题标题】:The argument types 'Edm.String' and 'Edm.Int32' are incompatible for this operation参数类型“Edm.String”和“Edm.Int32”与此操作不兼容
【发布时间】:2016-12-14 10:43:48
【问题描述】:

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

的位置

返回视图(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是什么类型的?
  • 它只是主键
  • 你的类中键的数据类型是什么。 (查看 edmx 或您的代码文件中的字段属性)

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


【解决方案1】:

当您的实体主键属于 A 类型并且您将非 A 类型的变量传递给 Find 方法时,通常会发生此异常。

Find方法的official documentation,可能会抛出如下异常

InvalidOperationException

如果键值的类型与键值的类型不匹配则抛出 要查找的实体类型的键值。

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

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

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

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

【讨论】:

  • 感谢您的建议,我是 mvc 新手。请问什么是A型。
  • 它可以是任何类型(例如:Guid)。在您的代码中,您正在传递一个 int 变量。检查 edmx 文件中的实体类以查看它是什么类型
  • 是的,我没有将它声明为 int。我被声明为 varchar(50) 。现在我将传递什么值而不是 0。
【解决方案2】:

您似乎正在遵循 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; }
}

【讨论】:

    【解决方案3】:

    Find() 将只接受数据类型类似于您将使用Find() 的表的主键的参数。

    【讨论】:

      猜你喜欢
      • 2013-12-10
      • 2013-09-15
      • 1970-01-01
      • 2013-01-19
      • 2018-07-17
      • 2015-12-28
      • 1970-01-01
      • 1970-01-01
      • 2015-05-13
      相关资源
      最近更新 更多