这是我和我应该如何质疑。
我有一个方法,我首先要检查数据库中是否存在对象。如果是,则使用对象中的“属性”更新该条目。如果没有,则将该对象添加到数据库。这适用于MVC中的模型对象。因此,我不想写出另一个Linq查询,而是简单地调用Get()函数,然后更新返回的对象。
示例:
Class CustomerController
Function GetCust(cust As Customer) As Customer
Dim db = New DataContext()
'assume primary key is compared to it's not null default instead of Nothing'
Return (From theCust In db.Customer
Where (cust.Property1 IsNot Nothing AndAlso theCust.Property1 = cust.Property1) _
AndAlso (cust.Property2 IsNot Nothing AndAlso theCust.Property2 = cust.Property2)
'etc
Select theCust).SingleOrDefault()
End Function
Function InsertOrUpdateCust(cust As Customer)
Dim db = New DataContext()
Dim retCust = GetCust(cust)
If retCust IsNot Nothing Then
retCust.Property1 = cust.Property1
retCust.Property2 = cust.Property2
'etc
Else
db.Customer.InsertOnSumbit(cust)
End If
db.SubmitChanges()
End Function
End Class
InsertOrUpdateCust函数就是我喜欢做的事情。所以我不必从GetCust获得两个查询实例。由于GetCust返回的Customer对象来自不同的DataContext,因此它不会附加到InsertOrUpdateCust函数中的DataContext。
我在.Attach()上找到了很多东西,但是问题和答案似乎都混淆了如何/何时使用它。那会有用吗?如果是这样,怎么样?或者我可以像这样传递DataContext吗?
Function GetCust(cust As Customer, Optional dContext As DataContext = Nothing)
Dim db = If(dContext Is Nothing, New DataContext(), dContext)
Return thequery.SingleOrDefault()
End Function
或者我应该停止尝试并只是复制查询?
这来自XLS任务的导入,其中插入/更新是最好的,但也许这种事情更有用。
谢谢!