如何使用实体框架更新现有Customer对象,插入新计算机对象和添加新WorkOrder?
Using trans As New System.Transactions.TransactionScope()
Using dcLAIT As LAITEntities = New LAITEntities
-- Update Customer (Apply existing Customer)
vWorkOrder.Customer = vCustomer
-- Insert Computer
vWorkOrder.Computer = vComputer
-- Insert WorkOrder
dcLAIT.WorkOrder.AddObject(vWorkOrder)
dcLAIT.SaveChanges()
trans.Complete()
End Using
End Using
答案 0 :(得分:2)
在将Customer
连接到已添加的WorkOrder
之前,您必须单独附加Using trans As New System.Transactions.TransactionScope()
Using dcLAIT As LAITEntities = New LAITEntities
-- Insert Computer
vWorkOrder.Computer = vComputer
-- Insert WorkOrder
dcLAIT.WorkOrder.AddObject(vWorkOrder)
dcLAIT.Customer.Attach(vCustomer)
-- Update Customer (Apply existing Customer)
dcLAIT.ObjectStateManager.ChangeObjectState(vCustomer, EntityState.Modified)
vWorkOrder.Customer = vCustomer
dcLAIT.SaveChanges()
trans.Complete()
End Using
End Using
并设置其状态:
SaveChanges
顺便说一下。 SaveChanges
在内部使用事务,因此除非您想强制序列化隔离级别,否则您将调用该范围内的多个TransactionScope
{{1}}是多余的。
答案 1 :(得分:0)
当您调用SaveChanges()时,应执行Context上的所有挂起更改。但是,如果数据库生成唯一ID,则在插入两个新的相关实体时,可能必须将插入和更新拆分为单独的调用。