I need some more understanding of how Entity Framework works. I have implemented code which is running ok and doing the job.
But I need to know that it is the good way or not.
I have a table with 8 columns, say
Table1
- Column1 (pk)
- Column2, Column3, Column4, Column5, Column6, Column7, Column8
Now when I click a button, I need to insert (if new) or update (for existing record) first 6 columns.
And on the same button click event, as part of the same process, I will call a stored procedure (with a parameter of primary key id, Column1
) that will fetch these 6 columns values in the stored procedure itself and will do some calculations based on six column values and return two new values which I need to update in Column7, Column8.
So, process will be:
New record: insert (six columns data), calculations (call stored procedure), update (last 2 column)
Existing record: update (six columns data), calculations (call stored procedure), update(last 2 column)
Now, for insert, I use
_dbContext.Table1.Add(entity);
_dbContext.SaveChanges();
For existing record update (of first 6 columns), I use
//code - Entity property values are updated with new ones
_dbContext.Table1.Attach(entity);
_dbContext.Entry(entity).State = EntityState.Modified;
_dbContext.SaveChanges();
For last update, Column7, Column8, I use
var entity = GetById(Id);
if (entity != null)
{
entity.Column7 = value1;
_dbContext.Entry(entity).Property(t => t.Column7).IsModified = true;
entity.Column8 = value2;
_dbContext.Entry(entity).Property(t => t.Column8).IsModified = true;
_dbContext.SaveChanges();
}
I am not sure why I need not to attach entity for last update. Is it due to I have called GetById
method for same table just above that?
Without attaching entity how it updates columns? (if I attach entity it gives error saying already being tracked)
Also, I have to call GetById
multiple times to get record for both updates (in existing record scenario). Any other solution for that?