0

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

user3428422
  • 4,300
  • 12
  • 55
  • 119
  • You still can send the entity via viewData or TempData – user28470 Oct 01 '14 at 08:16
  • Sending the entity information via a viewmodel works as all of the other properties in the entity are rendered correctly on the view, its just the ID never is.. – user3428422 Oct 01 '14 at 08:17
  • Are you sure you get the id after insertion? http://stackoverflow.com/questions/5212751/how-can-i-get-id-of-inserted-entity-in-entity-framework – user28470 Oct 01 '14 at 08:27
  • Positive, I used a breakpoint on the return View(viewModel) and the ID does have the correct ID. Will check the link, thanks – user3428422 Oct 01 '14 at 08:39
  • Oh wait i justn oticed you are calling `m.Entity.ID` I think it's `m.ID` – user28470 Oct 01 '14 at 08:49
  • I can see why you have said that but I put entity as I have another entity inside the viewmodel, entityA and entityB, hence why its the entity class then the .id, cheers though! – user3428422 Oct 01 '14 at 08:50
  • I guess in your view you have `@model myapp.Models.Entity` at the begining ? so you can call it like `@Model.ID` normally – user28470 Oct 01 '14 at 08:51
  • I have @model myapp.domain.ViewModel (so basically the two entities wrapped) – user3428422 Oct 01 '14 at 08:52

0 Answers0