使用System.Guid作为ASP.Net MVC中的主键?

Bin*_*fit 7 asp.net-mvc controller guid primary-key

我在数据库中创建了一个表,它有一个System.Guid作为它的主键.已生成所需的ADO.Net实体框架模型,并已映射所需的存储过程.

我创建了一个新的控制器,并为数据的创建和编辑添加了基本的必需代码.但是,当单击链接以编辑特定记录时,会生成以下错误:

The parameters dictionary contains a null entry for parameter '[MyId]' of non-nullable type 'System.Guid' for method 'System.Web.Mvc.ActionResult Edit(System.Guid)' in '[MySite].[MyController].[SpecificController]'. To make a parameter optional its type should be either a reference type or a Nullable type. Parameter name: parameters

编辑操作在控制器中声明如下:

public ActionResult Edit(Guid itemId)
{
    return View();
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(MyItem itemToModify)
{

}
Run Code Online (Sandbox Code Playgroud)

添加新记录时,通过存储过程生成新Guid,列表显示正确的Guid.Url也传递正确的Guid进行检索.

我似乎无法捕捉到失败的重点,但我如何将System.Guid作为参数传递给Controller?

tva*_*son 17

除非您已更新路由,否则(默认情况下)期望路由中的最终参数命名为"id".也就是说,如果你有/ specific/edit/5646-0767 -...这样的路由,它会将guid映射到带有键"id"的路由值字典,而不管你的方法中的参数是什么命名.我遵循这个约定并将方法定义更改为:

public ActionResult Edit(Guid id)
Run Code Online (Sandbox Code Playgroud)

您可以通过显式指定路由参数的名称来解决这个问题,但最后会得到一个类似于以下内容的网址:/ specific/edit?itemid = 5646-0767 -...