使用GUID作为ASP.NET MVC数据库中的ID

And*_*ers 5 asp.net-mvc guid

我正在学习ASP.NET MVC.我正在关注asp.net上的一个基本教程.由于我并不总是遵循教程,所以我决定使用GUID作为标识列而不是整数.一切正常,直到我通过MVC应用程序向数据库添加新记录.当我添加新记录时,它插入了一个空白GUID而不是生成的GUID.以下是处理插入的代码隐藏段:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create([Bind(Exclude = "id")]Movie movieToCreate)
{
    try
    {
        _entities.AddToMovieSet(movieToCreate);
        _entities.SaveChanges();

        return RedirectToAction("Index");
    }
    catch
    {
        return View();
    }
}
Run Code Online (Sandbox Code Playgroud)

[Bind(Exclude = "id")]行'忽略'ID列,因为它是自动生成的.在本教程中,ID是自动递增的,但我认为这是因为它是一个整数.我尝试在此方法中添加一行:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create([Bind(Exclude = "id")]Movie movieToCreate)
{
    try
    {
        movieToCreate.id = Guid.NewGuid();
        _entities.AddToMovieSet(movieToCreate);
        _entities.SaveChanges();

        return RedirectToAction("Index");
    }
    catch
    {
        return View();
    }
}
Run Code Online (Sandbox Code Playgroud)

但是id仍然是一个空的GUID.任何人都可以向我提供一些信息,说明为什么会这样,也许如何解决它?

swi*_*ams 6

您可以使用自定义ModelBinder.我在这里了解到了那些人.

public class MyClassBinder : DefaultModelBinder {
    protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) {
        var model = (Movie)base.CreateModel(controllerContext, bindingContext, modelType);
        model.id = Guid.NewGuid();
        return model;
    }
}
Run Code Online (Sandbox Code Playgroud)

你的行动控制器将是:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult MyAction(Movie movieToCreate) {
    // movie should have a new guid in the id
    _entities.AddToMovieSet(movieToCreate);
    _entities.SaveChanges();
}
Run Code Online (Sandbox Code Playgroud)

你需要在Global.asax中注册绑定器:

protected void Application_Start() {
    RegisterRoutes(RouteTable.Routes);
    ModelBinders.Binders.Add(typeof(Movie), new MyClassBinder());
}
Run Code Online (Sandbox Code Playgroud)