0

When creating a new database entry, how would I get the primary key, in this instance, called DocumentId as it is created and store it under another variable.

Here is my code to create the new database entry, the RevisionId is showing up as 0 because it cannot find the DocumentId, the primary key that is automatically incremented each time a new entry is entered. How do I get the number from the DocumentId?

if (ModelState.IsValid)
{
    documentUps.RevisionId = documentUps.DocumentId; //PROBLEM HERE SHOWS 0
    documentUps.Username = User.Identity.Name;
    documentUps.Attachment = file.FileName;
    documentUps.creationDate = DateTime.Now;
    documentUps.ActivationDate = DateTime.Now;
    documentUps.RevisionNumber = 0;
    documentUps.Status = StatusChoice.Draft;

    db.DocumentUps.Add(documentUps);
    db.SaveChanges();

    return RedirectToAction("Index");
}
  • It depends on how is this achieved in the database. In SQL Server, this is normally through an IDENTITY field. Here's a link on how that can be achieved, but you might need some extra model configuration: http://stackoverflow.com/questions/113928/can-i-return-the-id-field-after-a-linq-insert. If this link doesn't answer your question, please explain how this is configured in the DB and how it is configured in your model classes – Nick.Mc Mar 12 '17 at 23:29
  • @Nick.McDermaid that answers my question perfectly, I need to find the ID After I saved it to the database. Actually makes sense when I think about it haha, thanks – Captain Canada Mar 12 '17 at 23:35
  • Glad you solved it. I'll mark it as a duplicate. In future please at least tag the database. You might want consider improving your google-fu – Nick.Mc Mar 12 '17 at 23:36
  • 1
    Possible duplicate of [Can I return the 'id' field after a LINQ insert?](http://stackoverflow.com/questions/113928/can-i-return-the-id-field-after-a-linq-insert) – Nick.Mc Mar 12 '17 at 23:37
  • Please note that the model-view-controller tag is for questions about the pattern. There is a specific tag for the ASP.NET-MVC implementation. –  Mar 13 '17 at 05:29

0 Answers0