Entity framework 4 存储库&x2B;工作单位+;EF在详细记录更改时更新主记录。(总金额=总和(金额))
我正在尝试使用实体框架实现存储库和UnitOfWork模式 这是一个场景: 用户可以在主详细信息窗口中添加或修改详细信息记录,当点击“保存”时,添加/修改的记录将发送到服务器 然后执行CreateOrUpdateMultiple()。 CreateMultiple将新记录添加到存储库。 UpdateMultiple检索要更新的记录 在这两个操作完成后,我需要使用包含所有详细记录的总和(字段)更新主记录。(我指的是没有被修改的现有的和内存中的) 这就是我到目前为止的想法Entity framework 4 存储库&x2B;工作单位+;EF在详细记录更改时更新主记录。(总金额=总和(金额)),entity-framework-4,repository-pattern,unit-of-work,Entity Framework 4,Repository Pattern,Unit Of Work,我正在尝试使用实体框架实现存储库和UnitOfWork模式 这是一个场景: 用户可以在主详细信息窗口中添加或修改详细信息记录,当点击“保存”时,添加/修改的记录将发送到服务器 然后执行CreateOrUpdateMultiple()。 CreateMultiple将新记录添加到存储库。 UpdateMultiple检索要更新的记录 在这两个操作完成后,我需要使用包含所有详细记录的总和(字段)更新主记录。(我指的是没有被修改的现有的和内存中的) 这就是我到目前为止的想法 作为存储库模式的纯粹主义者
//Service Layer
Method()
{
Method1.Invoke(masterRecordId, detaildRecords); //
}
//Business Layer
Method1(masterRecordId, detailRecords)
{
using(TransactionScope ts = new TransactionScope())
{
var recordsToUpdate = dal.RetrieveOnlyRecordsToUpdate();
//Update retrieved records with the values of recods comming from the client
dal.Update(recordsToUpdate); //ctx.ApplyChanges(); and ctx.SaveChanges();
dal.Add(recordsToAdd) //ctx.Add(detail records); and ctx.SaveChanges();
//Update master record TotalSum
dal.UpdateMasterRecord(masterRecordId); //Here is performed ctx.ExecuteStoredCommand("UPDATE MasterTable = SUM() WHERE MasterRecordId = {0}")...
Method2();
ts.Complete();
}
}
Method2(masterRecordId)
{
using(TransactionScope ts = new TransactionScope())
{
MasterRecord m = Retrieve(masteRecordId);
Notification notification = new Notification(){ ...assign properties..., m.TotalSum};
dal.Add(notification); //ctx.Add(notification); and ctx.SaveChanges();
ts.Complete();
}
}
这就是我想做的
//Service Layer
Method()
{
Method1.Invoke(masterRecordId, detail records);
UnitOfWorkManager.Current.Commit(); //
}
//Business Layer
Metodo1(masterRecordId, detail records)
{
MasterRecord masterRecord = repository.Retrieve(masterRecordId);
var recordsToUpdate = repository.RetrieveOnlyRecordsToUpdate();
//Update retrieved records with the values of recods comming from the client
repository.Modify(recordsToUpdate);
repository.Add(recordsToAdd);
//Here i'm stuck and i'm thinking it should be something like this.
masterRecord.TotalSum = sum(detailRecords in memory + detail records in database); //
repository.Modify(masterRecord); //
or
//Another way somehow...
//Then keep going with the udpated master record
Method2(masterRecord);
}
}
Method2(masterRecord)
{
//Create notification
var notification = new Notification(){ ...properties.., masterRecord.TotalSum};
repository.Add(notification);
}
如果您想以事务的形式执行此操作并仅调用一次
SaveChanges
,则必须在调用SaveChanges
之前在应用程序中执行此操作。所以,一般来说,在进行任何更改之前,您必须先获取总和,然后再通过更新值、插入值和删除值修改总和。然后将新的总和值设置到主记录中。如果你这样做,你将有一个单位的工作
为什么其他方法不那么好
- 数据库中的计算字段。这将需要在保存操作后手动重新加载主实体,因为保存详细信息无法重新加载其他实体中的更改。此外,数据库逻辑可能需要细节表上的触发器来修改主表中的总和
- 保存对详细信息的更改后更新主记录会中断工作单元