在ASP.NET MVC中使用GUID作为数据库中的ID [英] Using a GUID as the ID in a database with ASP.NET MVC
问题描述
我正在学习ASP.NET MVC.我正在遵循 asp.net 上的基本教程之一.由于我并不总是按照这些教程进行操作,因此我决定使用GUID作为标识列,而不是整数.一切工作正常,直到我可以通过MVC应用程序向数据库添加新记录为止.当我添加新记录时,它插入了一个空白的GUID而不是一个生成的GUID.这是处理插入的代码段:
I am learning ASP.NET MVC. I am following one of the basic tutorials on asp.net. Since I do not always follow the tutorials to the letter, I decided to use a GUID as the identity column instead of an integer. Everything was working fine until I got up to the point of adding a new record to the database through the MVC application. When I added the new record, it inserted a blank GUID instead of a generated one. Here is the segment of code-behind that handles the insertion:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create([Bind(Exclude = "id")]Movie movieToCreate)
{
try
{
_entities.AddToMovieSet(movieToCreate);
_entities.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
[Bind(Exclude = "id")]
行忽略" ID列,因为它是自动生成的.在本教程中,ID是自动递增的,但是我认为这是因为它是一个整数.我尝试在此方法中添加一行:
The [Bind(Exclude = "id")]
line 'ignores' the ID column, since it is autogenerated. In the tutorial, the ID is auto-incremented but I think that is because it is an integer. I tried adding a line to this method:
[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();
}
}
但是ID仍然是空的GUID.谁能为我提供一些有关这是为什么以及可能如何解决的信息?
But the id is still an empty GUID. Can anyone provide me with some information on why this is and perhaps how to resolve it?
推荐答案
您可以使用自定义ModelBinder.我通过此处了解了这些信息.
You could use a custom ModelBinder. I learned about those over here.
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;
}
}
您的动作控制者将是:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult MyAction(Movie movieToCreate) {
// movie should have a new guid in the id
_entities.AddToMovieSet(movieToCreate);
_entities.SaveChanges();
}
并且您需要在Global.asax中注册活页夹:
And you would need to register the binder in Global.asax:
protected void Application_Start() {
RegisterRoutes(RouteTable.Routes);
ModelBinders.Binders.Add(typeof(Movie), new MyClassBinder());
}
这篇关于在ASP.NET MVC中使用GUID作为数据库中的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!