6

I have a table "JobOrder" which is added to the database using normal EF call.
In my database, i have the Job_Id as primary key & auto increment value so i do not need to set it which the EF model defaults it to 0.
But I am in need of the Job_Id that has been inserted to database after i call SaveChanges().
I tried using Refresh() but it did not work, the Job_Id for newly inserted object was still 0.

using (ObjContext context = new ObjContext())  
{  
    context.AddToJobOrder(order);  
    context.SaveChanges();
    context.Refresh(RefreshMode.StoreWins, order);             //TRIED THIS  
    context.Refresh(RefreshMode.StoreWins, context.JobOrder);  //TRIED THIS TOO  
}

I tried both calls as mentioned above, but still i ended up having Job_Id to be 0.
Any help would be greatly appreciated.

Rais Alam
  • 6,970
  • 12
  • 53
  • 84
Rahul
  • 61
  • 2
  • Did you generate the model from database the normal way from the designer and not tweaking it manually? Does the SaveChanges() write the data into the database? – 0x49D1 Apr 11 '11 at 07:33
  • Yes i generated it using the wizard. Made no changes to the xml. Yes the SaveChanges() does write the data into the database. – Rahul Apr 11 '11 at 08:21

3 Answers3

1

In a normal situation you dont need Refresh method. After context.SaveChanges() that newly inserted order must have its proper order.Job_id. Sure if you have MSSQL database..In other cases there can be some unimplemented things in providers, tho for now almost all major DB vendors have at least normal beta versions of DB providers with support of common EF features.
PS there are many similar questions over the net and on stack overflow too.. See this for example.

Community
  • 1
  • 1
0x49D1
  • 8,505
  • 11
  • 76
  • 127
1

When you add an object to the context, and SaveChanges() it should correctly populate the ID field.

So try this, set a breakpoint and you'll see the primary key ID is set correctly.

using (ObjContext context = new ObjContext())  
{  
    context.AddToJobOrder(order);  
    context.SaveChanges();

    //Breakpoint here, and see that Job_id has been populated.
    Debug.WriteLine(order.Jod_id);
}

Only after .SaveChanges does the primary key get set, because it has to go the database and find the next numerical value.

Only Bolivian Here
  • 35,719
  • 63
  • 161
  • 257
  • Check the entity model and ensure StoreGeneratedPattern is set to identity for the primary key for that object / table. – Rob Jul 27 '21 at 17:29
0

Make sure it has the StoreGeneratedPattern property set to Identity in both the CSDL and SSDL. The designer shows only the CSDL property so you may need to open it up in the XML editor to look at and edit the SSDL, or use a sync tool (e.g. my add-in's model comparer for EF4) to keep the DB/SSDL/CSDL in sync.

KristoferA
  • 12,287
  • 1
  • 40
  • 62