更新 SqlCE 数据库 Linq-to-Sql
当我更新数据库时,我必须对每个属性的映射进行硬编码,因为使用附加会导致异常。这看起来不太优雅。这里有一些我不知道的更简单的解决方案吗?我的代码如下,显示了我为此目的调用的“MapData”方法:
顺便说一句,实体类(此处为“用户”)是使用 SqlMetal 自动生成的。
Public Class UserDataService
Public Sub Save(ByVal user As Users)
Dim ctx As New TestDB(connection)
Dim id As Integer = user.Id
If user.Id = 0 Then
Insert(user)
Else
Dim q = (From n In ctx.Users Where n.Id = id Select n).Single
q.MapData(user)
For Each o In user.Orders
o.Save()
Next
' ctx.Users.Attach(user, q) ' Does not work
' ctx.Users.Attach(user, True) ' Does not work
End If
ctx.SubmitChanges()
ctx.Dispose()
End Sub
End Class
Partial Public Class Users
Public Sub MapData(ByVal row As Users)
Me.Name = row.Name
End Sub
End Class
EDIT1:
例外:
ctx.Users.Attach(user, q)
无法添加具有已在使用的密钥的实体。
ctx.Users.Attach(user, True )
如果实体声明版本成员或没有更新检查策略,则只能在没有原始状态的情况下附加修改后的实体。
编辑2:
我尝试添加列时间戳,我相信这应该满足最后提到的例外。所以我添加了此处显示的列。这没有帮助,但也许我需要进行一些进一步的设置才能使其有效?
When I update the database, I have to hard code mapping of each property, because using attach results in exception. This does not seem too elegant. Is there some easier solution here I'm not aware of? My code is below, showing the "MapData" method I call for this purpose:
Btw, entity classes (here; Users) are autogenerated with SqlMetal.
Public Class UserDataService
Public Sub Save(ByVal user As Users)
Dim ctx As New TestDB(connection)
Dim id As Integer = user.Id
If user.Id = 0 Then
Insert(user)
Else
Dim q = (From n In ctx.Users Where n.Id = id Select n).Single
q.MapData(user)
For Each o In user.Orders
o.Save()
Next
' ctx.Users.Attach(user, q) ' Does not work
' ctx.Users.Attach(user, True) ' Does not work
End If
ctx.SubmitChanges()
ctx.Dispose()
End Sub
End Class
Partial Public Class Users
Public Sub MapData(ByVal row As Users)
Me.Name = row.Name
End Sub
End Class
EDIT1:
Exceptions:
ctx.Users.Attach(user, q)
Cannot add an entity with a key that is already in use.
ctx.Users.Attach(user, True)
An entity can only be attached as modified without original state if it declares a version member or does not have an update check policy.
EDIT2:
I tried to add a column timestamp, which I believe is supposed to satisfy the last mentioned exception. So I add the column shown here. This doesn't help, but perhaps I need to make some further settings for that to be effective?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这种方式应该可以工作:
这是我的控制台测试应用程序(它可以工作),但在 C# 中:
This way should work:
This is my console test app(it works), in C# though: