[英]Unit of work + repository pattern + entity framework 4 : Dependancy of records which is not yet saved in database in sigle transaction
I am working on MVC4 application with Unit of work + generic repository pattern + entity framework 4 . 我正在使用工作单元+通用存储库模式+实体框架4开发MVC4应用程序。
Now i want to insert / update employee leave records in a table based on some logic from excel file. 现在,我想基于Excel文件中的某些逻辑在表中插入/更新员工请假记录。
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. 现在插入记录的逻辑是:1)如果一个记录的DOT与下一个记录的DOH之差小于2周,则我们必须用第二个记录DOT更新第一个记录DOT。 and delete the second record 2) else update record which is overlapping with record in table
并删除第二条记录2)else更新与表中的记录重叠的记录
now in one excel sheet file there are two records for same employee 现在在一个excel工作表文件中,同一位员工有两条记录
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; 现在按照该示例,当将excel中的第一条记录与数据库记录进行比较时,当事务完成时,它将从表中删除第二条记录; 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.
当将excel中的第二条记录与第二条记录进行比较时,它只会尝试更新第二条记录,但是表中的第二条记录在第一次DML操作中被excel文件中的第一条记录删除。
So what is workaround for this situation ? 那么,这种情况下的解决方法是什么?
do i need to call unitofwork.save(); 我需要调用unitofwork.save();吗? after each loop?
每个循环之后? in that case what if there is error while processing second record from excel file ?
在这种情况下,如果处理excel文件中的第二条记录时出现错误怎么办? i want all file records to be processed or nothing.
我希望所有文件记录都得到处理或什么都没有。
Thanks, Amol 谢谢阿莫
do i need to call unitofwork.save();
我需要调用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. 使用
EntityState
或创建您自己的状态。
Then in DeleteEntity(Entity entity)
method set 然后在
DeleteEntity(Entity entity)
方法中设置
entity.State = EntityState.Deleted;
and then ignore deleted object in your second condition. 然后在第二种情况下忽略已删除的对象。
At the end commit data, so EF saves all changes. 最后提交数据,因此EF保存所有更改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.