我有一项更新客户地址的服务。要限制数据库中的更改(并有一个干净的审计/更改日志),我不想更新最新的字段。
实体联系,使用 CustomerAddress (MS Dynamics实体)进行更新。
(另一种解决方案可能是我不知道的实体框架标志。)
我目前有:
Dim newcontact = new Contact with {.id = (someguid)}
Dim oldcontact = obtainOldContact(someguid)
Dim customerUpdate = obtainChange(someguid)
if oldcontact.City <> customerUpdate.City then
newContact.City = customerUpdate.City
end if
[repeat for about 12 fields)
(我觉得有些可怕)
一个简单的解决方案是:
Dim newcontact = new Contact with {.id = (someguid)}
Dim oldcontact = obtainOldContact(someguid)
Dim customerUpdate = obtainChange(someguid)
Dim isDirty as boolean = false
if oldcontact.City <> customerUpdate.City then
newContact.City = customerUpdate.City
isDirty = true
end if
[repeat for about 12 fields)
(我觉得太可怕了)
我要做的是检查我的可能更新的字段是否有值,但我无法弄清楚:
'newcontact = my contact to _maybe_ save...)
dim listProp = {"Adress1Line1", "Adresse1Line2", "PostalCode", "City"}
for each properties in listProp
if eval(newcontact & "." & properties) isnot nothing then ' <- kinda what I wanna do
'update and exit for
end if
next
欢迎任何优雅的解决方案。
答案 0 :(得分:1)
我跟随j.f。对GetProperties()
的评论。
这是我最终如何做到的:
Private Function UpdateProperties(Of T)(fieldList As Dictionary(Of String, String), Current As T, UpdateObject As T, Change As CustomerAddress) As Boolean
Dim isDirty = False
Dim PropList = GetType(T).GetProperties()
Dim CustomerPropList = GetType(CustomerAddress).GetProperties()
For Each item In fieldList
Dim prop = item
Dim propT = PropList.Single(Function(e) e.Name = prop.Value)
Dim propCustomer = CustomerPropList.Single(Function(e) e.Name = prop.Key)
Dim val As String = TryCast(propT.GetValue(Current, Nothing), String)
Dim valCustomer As String = TryCast(propCustomer.GetValue(Change, Nothing), String)
If val <> valCustomer Then
propT.SetValue(UpdateObject, valCustomer, Nothing)
isDirty = True
End If
Next
Return isDirty
End Function
哪里
fieldList
是一个字典,用于将我的第一个对象的字段(联系人/帐户)映射到第二个对象的字段(CustomerAddress)。Current
是我目前为客户保存的内容UpdateObject
是一个空对象,仅包含已更改的信息Change
是收到的信息,我可能需要用它来更改我当前的数据(如果不同)