EF does not update the primary key of an object recently added to the database

I have a table called "JobOrder" that is added to the database using a regular EF call.
In my database, I have Job_Id as the primary key and auto increment value , so I do not need to set it, by default for the EF model it is 0.
But I need Job_Id, which was inserted into the database after calling SaveChanges ().
I tried using Refresh (), but that did not work, Job_Id for the newly inserted object is 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 Job_Id equal to 0.
Any help would be greatly appreciated.

+5
source share
3 answers

In a normal situation, you do not need the Refresh method. After context.SaveChanges()that, the new inserted order should have its own order.Job_id. Of course, if you have an MSSQL database. In other cases, providers may have some unrealized things. At the moment, almost all major database providers have at least regular beta versions of database providers with support for common EF features.
PS there are many similar questions on the network and when the stack overflows. For example, this .

+1
source

When adding an object to the context, SaveChanges()it must correctly fill in the ID field.

, , , , .

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);
}

.SaveChanges , .

+1

Ensure that the StoreGeneratedPattern property is set to Identity in both CSDL and SSDL. The designer only shows the CSDL property, so you may need to open it in an XML editor to view and edit the SSDL or use a synchronization tool (like my add-in for EF4) to synchronize DB / SSDL / CSDL.

0
source

All Articles