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.
You cannot update a primary key, but that is not a limitation of entity framework, but a very fundamental rule of database development. A primary key is assigned once to a row in a table and makes this row unique. Maybe you can update the key in some ways, but this violates definitely the definition of a primary key.
We can update records either in connected or disconnected scenarios. In the connected Scenario, we open the context, query for the entity, edit it, and call the SaveChanges method. In the Disconnected scenario, we already have the entity with use. Hence all we need to is to attach/add it to the context.
State = EntityState. Modified; , you are not only attaching the entity to the DbContext , you are also marking the whole entity as dirty. This means that when you do context. SaveChanges() , EF will generate an update statement that will update all the fields of the entity.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With