Reputation: 1004
I am working on MVC4 application with Unit of work + generic repository pattern + entity framework 4 .
Now i want to insert / update employee leave records in a table based on some logic from excel file.
for example
now the logic to insert record is that 1) if difference between DOT one record and DOH of next record is less than 2 weeks then we have to update the first record DOT with second record DOT. and delete the second record 2) else update record which is overlapping with record in table
now in one excel sheet file there are two records for same employee
code
List<Employeeleave> lstEmp = unitofwork.employeeleaveRepository().get(x=>x.id==empid)
for( var emp in Employeeleave)
{
// for each record check the diffrence between DOT of this record if avaialble amd DOH of next record
// if valid as per logic then update current and delete next record
}
unitofwork.save(); //save all DML at once
now as per this example when first record in excel is compared with database records it deletes the second record from table when transaction is complete; and when second record from excel is compared with second record it will simply try to update the second record but second record in table is being deleted by first record in excel file in first DML operation.
So what is workaround for this situation ?
do i need to call unitofwork.save(); after each loop? in that case what if there is error while processing second record from excel file ? i want all file records to be processed or nothing.
Thanks, Amol
Upvotes: 1
Views: 423
Reputation: 9139
do i need to call unitofwork.save(); after each loop?
This is bad approach, avoid it. Every call to database is resource greedy.
By adding flag with object state you can simply solve the problem.
Use EntityState
or create your own status.
Then in DeleteEntity(Entity entity)
method set
entity.State = EntityState.Deleted;
and then ignore deleted object in your second condition.
At the end commit data, so EF saves all changes.
Upvotes: 1