asp.net-mvc - 在 ASP.Net MVC 中使用 System.Guid 作为主键?

标签 asp.net-mvc controller primary-key guid

我在数据库中创建了一个以 System.Guid 作为主键的表。已生成所需的 ADO.Net Entity Framework 模型并已映射所需的存储过程。

我创建了一个新 Controller 并为数据添加了创建和编辑所需的基本代码。但是,当单击链接编辑特定记录时,会生成以下错误:
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
编辑 Action 在 Controller 中声明如下:

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

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

}

添加新记录时,新的 Guid 是通过存储过程生成的,并且列表显示正确的 Guid。 Url 还传递了正确的 Guid 以进行检索。

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

最佳答案

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

public ActionResult Edit(Guid id)

您可以通过显式指定路由参数的名称来解决此问题,但最终会得到一个如下所示的 url:/specific/edit?itemid=5646-0767-...

关于asp.net-mvc - 在 ASP.Net MVC 中使用 System.Guid 作为主键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1483467/

相关文章:

ruby-on-rails - 如何验证 Rails Controller 中的存在和正则表达式格式?

mysql - MySQL数据库中指定的两个主键

asp.net-mvc - 如何在 ASP.NET MVC 中上传图像?

c# - 在 ASP.NET MVC 中将 AutoMapper QueryableExtensions 与 Entity Framework 一起使用会导致 "Operation could destabilize the runtime"异常

c# - 带有 cookie 身份验证的 ASP.Net Core 2.2 : how to avoid page redirect when not authorized for API only controllers

php - laravel 5.4 自动重定向到 404 页面

c# - MVC 3与ajax提交复杂对象到 Controller

mysql - 我应该将哪些列添加到 PRIMARY KEY

java - 如何返回 java 中最后添加的项目的最后一个主键?

c# - 如何编写自己的 AuthorizeTag?