Entity framework 对新EntityType变量的更改更新源对象
(更新:在初始代码块后添加了变通方法) 我不是说有什么不对,只是不明白这是怎么回事 使用Visual Studio 2012 Express for Windows桌面和 实体框架5 我有一个新的windows窗体应用程序,其中有一个窗体FrmHome,在应用程序启动时运行。 我有一个叫做GrowModel的概念模型。 我有一种叫做Plant的实体类型。 Plant有两个属性Id和名称。 假设工厂中有一些记录 由以下代码引发的messagebox为currentPlant.Name和plantCopy.Name显示相同的值(“XXX”)。我认为,通过在声明plantCopy时使用New,可以获得Plant对象的单独副本,并且对plantCopy属性的更改不会影响currentPlant 有人能告诉我这是怎么回事吗 谢谢大家!Entity framework 对新EntityType变量的更改更新源对象,entity-framework,entity-framework-5,Entity Framework,Entity Framework 5,(更新:在初始代码块后添加了变通方法) 我不是说有什么不对,只是不明白这是怎么回事 使用Visual Studio 2012 Express for Windows桌面和 实体框架5 我有一个新的windows窗体应用程序,其中有一个窗体FrmHome,在应用程序启动时运行。 我有一个叫做GrowModel的概念模型。 我有一种叫做Plant的实体类型。 Plant有两个属性Id和名称。 假设工厂中有一些记录 由以下代码引发的messagebox为currentPlant.Name和plantC
Public Class FrmHome
Private Shared m_growData As New GrowEntities
Public Sub DoSomething() Handles Me.Load
Dim currentPlant As Plant
currentPlant = FindPlantById(1)
Dim plantCopy as New Plant
plantCopy = currentPlant
plantCopy.Name = "XXX"
MessageBox.Show("Current Plant Name: " & _
currentPlant.Name & ControlChars.CrLf & _
"Plant Copy Name:" & plantCopy.Name)
End Sub
Shared Function FindPlantById(ByVal PlantId As Integer) As Plant
Dim PlantList As New List(Of Plant)
PlantList = m_growData.Plants.ToList
Dim intPlantLoopCount As Integer = PlantList.Count - 1
For y = 0 To intPlantLoopCount
Dim currentPlant As Plant = PlantList(y)
If currentPlant.Id = PlantId Then
Return currentPlant
End If
Next
Return Nothing
End Function
End Class
(更新1)
目前,我使用下面的代码作为解决方法,因为您可以复制工厂的元素,而无需传递引用。请注意添加的CopyPlant函数及其在为plantCopy赋值时的使用。假定Plant命名为Notes和LastUpdate的两个附加属性。使用以下代码,plantCopy.Name为“XXX”,currentPlant.Name为“OriginalValue”。看起来你仍然可以在没有参考的情况下将一个工厂复制到另一个工厂,但是如果我必须做额外的工作,那么我会的
Public Class FrmHome
Private Shared m_growData As New GrowEntities
Public Sub DoSomething() Handles Me.Load
Dim currentPlant As Plant
currentPlant = FindPlantById(1)
Dim plantCopy as New Plant
plantCopy = CopyPlant(currentPlant)
plantCopy.Name = "XXX"
MessageBox.Show("Current Plant Name: " & _
currentPlant.Name & ControlChars.CrLf & _
"Plant Copy Name:" & plantCopy.Name)
End Sub
Shared Function FindPlantById(ByVal PlantId As Integer) As Plant
Dim PlantList As New List(Of Plant)
PlantList = m_growData.Plants.ToList
Dim intPlantLoopCount As Integer = PlantList.Count - 1
For y = 0 To intPlantLoopCount
Dim currentPlant As Plant = PlantList(y)
If currentPlant.Id = PlantId Then
Return currentPlant
End If
Next
Return Nothing
End Function
Shared Function CopyPlant(ByVal source As Plant) As Plant
Dim target As New Plant
target.Name = source.Name
target.Notes = source.Notes
target.LastUpdate = Now()
Return target
End Function
End Class
您正在覆盖引用,以便plantCopy和currentPlant都引用同一对象,并将您创建的Plant的单独副本替换为新副本
您可以使用来克隆对象,而不是复制引用,或者搜索许多类似的问题。将Dim plantCopy用作新的Plant是否会创建未引用的副本?我以为这就是新关键字的作用?很抱歉,我真的想按照你说的做,我正在看你的链接文章。行
Dim plantCopy as New Plant
确实创建了一个新的引用,但行plantCopy=currentPlant
将plantCopy设置为引用与currentPlant相同的对象,丢弃了新创建的对象。你的新版本可以用。