【问题标题】:Using a System.Guid as primary key in ASP.Net MVC?在 ASP.Net MVC 中使用 System.Guid 作为主键?
【发布时间】:2009-09-27 12:06:10
【问题描述】:

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

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

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)
{

}

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

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

【问题讨论】:

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


    【解决方案1】:

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

    public ActionResult Edit(Guid id)
    

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

    【讨论】:

    • 别担心——我知道答案的唯一原因是我曾经做过同样的事情并且必须弄清楚。
    【解决方案2】:

    将示例代码放在下面供任何可能需要的人使用(我确实这样做了)

            public ActionResult Profile(Guid? id)
        {
            if (!id.HasValue)
            {
                return View(new ProfileRepository().GetUserProfile(User.Identity.Name));
            }
    
            return View(new ProfileRepository().GetUserProfile(id.Value));
    
        }
    

    感谢您的上述回答,使我朝着正确的方向前进

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-16
      • 1970-01-01
      • 2014-04-04
      • 2017-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多