0

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?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
vibs
  • 115
  • 2
  • 14

2 Answers2

0

for that you can use MapToModel method

here is example

//code - Entity property values are updated with new ones
var newEntity= new Entity
{
    Id = p.Id, // the Id you want to update
    Column1= ""  // put value for column/s that you need to update
};
newEntity.MapToModel(oldEntity);
_dbContext.SaveChanges();
0

IMHO I don't think you need to specify IsModified for each property if you fetch through the Context.

EF Context will automatically track Entities unless you change the default behavior

EF knows which entities are changed after loading from the database,hence it will be only updated.

Assuming GetById is fetching the data from data-store.

var entity = GetById(Id);

if (entity != null)
{
    entity.Column7 = value1;
    entity.Column8 = value2;
    _dbContext.SaveChanges();
}

Detect Changes

Similar Question

Eldho
  • 7,795
  • 5
  • 40
  • 77