I am successfully saving a entity to my database and getting back the PK ID that the Database has generated.
repository.InsertOrUpdate(viewModel.Entity);
repository.Save();
viewModel.Entity.ID // This property will now have the ID that the database has generated.
So all well and good.
However, when I send the Veiwmodel back to the view from the controller
return View(viewModel);
and using
@Html.TextBoxFor(m => m.Entity.Id)
The ID appears as 0. So therefore when I try to post an update, EF thinks its a new record, using this syntax
public void InsertOrUpdate(Entity entity)
{
if (entity.Id == default(int))
{
entity.Created = DateTime.Now;
entity.LastEdit = DateTime.Now;
Context.T.Add(entity);
}
else
{
entity.LastEdit = DateTime.Now;
Context.Entry(entity).State = System.Data.Entity.EntityState.Modified;
}
}
Anything obvious I am doing wrong in which I can't get the created ID to the view?
**** Edit *****
Strangely, using
@Html.TextBoxFor(m => m.Entity.Id)
will show 0 as above. However, if I use
@Html.DisplayFor(m => m.Entity.Id)
It will show the correct ID value.. (Why?)
But when I press send the ActionResult post still returns 0...
Thanks