yandex
loader

please wait

  • Pooja Bhardwaj Mar-13-2019 06:16:10 AM ( 1 week 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(); 
    }
  • Shreya Bansal Mar-13-2019 06:17:57 AM ( 1 week 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);

Please login

Similar Discussion

Recommended For You