Get Autogenerated Guid- MVC
Does anyone happen to know if there is a way in the Entity Framework to return me the Guid of 开发者_运维百科a just inserted row, assume the column is an guid which is auto Generated.
I am using MVC with Entity Framework. I am using Repository Method ADD(), the return type of the method is void.
Any one knows?
StewieFG,
On adding the item, and hitting SaveChanges()
, your object should now be populated with the value of the autogenrated column. Consider the example below:
[HttpPost]
public ActionResult Create(MyEditViewModel viewModel)
{
if (ModelState.IsValid) {
_myService.Insert(viewModel.Entity);
_myService.SaveChanges();
// we can query the column value for the autogenerated value now
// i.e. viewModel.Entity.GuidIDColumn value etc..
return this.RedirectToAction(x => x.Index());
} else {
PopulateViewModel(viewModel);
return View(viewModel);
}
}
hope this helps
精彩评论