ASP.NET MVC 5, Entity Framework db.savechanges() returns wrong inserted id

General Tech Bugs & Fixes 2 years ago

0 2 0 0 0 tuteeHUB earn credit +10 pts

5 Star Rating 1 Rating

Posted on 16 Aug 2022, this text provides information on Bugs & Fixes related to General Tech. Please note that while accuracy is prioritized, the data presented might not be entirely correct or up-to-date. This information is offered for general knowledge and informational purposes only, and should not be considered as a substitute for professional advice.

Take Quiz To Earn Credits!

Turn Your Knowledge into Earnings.

tuteehub_quiz

Answers (2)

Post Answer
profilepic.png
manpreet Tuteehub forum best answer Best Answer 2 years ago

 

I'm using EF and ASP.NET MVC 5, and when inserting into database using

dbcontext.SaveChanges(mymodel)

the returned id is always "1", however in the SQL database, the inserted record's id is "3" (before inserting I deleted the first two records in the database table to clear the table).

Could anyone tell me how to fix this? I feel EF is not update to date with database or am missing any settings to sync both? Many thanks in advance...

My code below...

if (ModelState.IsValid)
{
    stodoc.StockOutDocument_Serial = srlnum;
    stodoc.StockOutDocument_date = inview.InventoryDate;

    db.StockOutDocuments.Add(stodoc);
    int stodocid = db.SaveChanges(); 
}
profilepic.png
manpreet 2 years ago

The ID of the newly created record doesn't come from the SaveChanges call. SaveChanges will update all modified/inserted/deleted records.

Provided you have configured your entity as recognizing it's ID is DatabaseGeneratedOption.Identity then to get the newly inserted ID:

            stodoc.StockOutDocument_Serial = srlnum;
            stodoc.StockOutDocument_date = inview.InventoryDate;
            db.StockOutDocuments.Add(stodoc);
            db.SaveChanges(); 
            int stodocid = stodoc.stodocid; // Will be populated once SaveChanges is called.

If the stodoc.stodocid property is not updated, check that you have configured it in the mapping as an Identity column:

If you used attributes in the entity:

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int stodocid { get; set; }

or via entity configuration: EF Core:

builder.HasKey(x => x.stodocid);
builder.Property(x => x.stodocid).UseSqlServerIdentityColumn();

EF6:

HasKey(x => x.stodocid)
    .Property(x => x.stodocid)
    .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

0 views   0 shares

No matter what stage you're at in your education or career, TuteeHub will help you reach the next level that you're aiming for. Simply,Choose a subject/topic and get started in self-paced practice sessions to improve your knowledge and scores.