LINQ到Sql更新内部循环

时间:2013-03-19 21:42:34

标签: .net vb.net linq-to-sql

我的问题是,如果我遍历我的集合,如下所示,并适当设置值,我需要在每次迭代结束时调用dc.SubmitChanges()才能使其正常工作吗?如果不这样做,它不会简单地覆盖Update上的先前值吗?

我正在将Contact对象传递给此Save()方法。该对象具有PersonContact属性,该属性又具有Phones属性。这是Save()方法的一部分,需要在我的对象中遍历Phones并将其与DB进行比较并采取相应的措施。

有更好,更简单的方法吗?

If contact.PersonContact.Phones IsNot Nothing Then
  For Each phone In contact.PersonContact.Phones
    Dim exists = dc.tblPhones.SingleOrDefault(Function(p) p.ID = phone.ID)
    If exists IsNot Nothing Then
        If phone.Number = String.Empty AndAlso phone.Extension = String.Empty Then
            'Delete
            dc.tblPhones.DeleteOnSubmit(exists)
        Else
            'Update
            exists.ID = phone.ID
            exists.PhoneNumber = phone.Number
            exists.TypeID = phone.TypeID
            exists.UpdateDate = DateTime.Now
            exists.UpdateUser = user
        End If
    Else
        'Insert
        exists = New tblPhone() With { _
            .ID = phone.ID, _
            .PhoneNumber = phone.Number, _
            .Extension = phone.Extension, _
            .TypeID = phone.TypeID, _
            .InsertDate = DateTime.Now, _
            .InsertUser = user, _
            .PersonID = contact.PersonContact.ID _
        }
        dc.tblPhones.InsertOnSubmit(exists)
    End If
  'Do I need to Save here???
  dc.SubmitChanges()
  Next
End If

0 个答案:

没有答案