Linq to SQL,一次插入前更新大量数据
在将新值插入表之前,我需要更改该表所有行中的一个字段。 做到这一点的最好方法是什么?在c#代码中,矿石使用触发器吗?如果是 C# 可以给我看一下代码吗?
UPD *问题的新版本* 你好。在将新值插入表之前,我需要更改该表的所有行中具有特定 ID 的一个字段(它是另一表的 FK)。 做到这一点的最好方法是什么?在c#代码中,矿石使用触发器吗?如果是 C# 可以给我看一下代码吗?
Before insert new value to table, I need change one field in all rows of that table.
What the best way to do this? in c# code, ore use trigger? if C# can you show me the code?
UPD
*NEW VERSION of Question*
Hello. Before insert new value to table, I need change one field in all rows of that table with specific ID( It is FK to another table).
What the best way to do this? in c# code, ore use trigger? if C# can you show me the code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可能应该考虑更改您的设计,这听起来似乎无法很好地扩展,如果总是需要的话,我可能会使用触发器来实现,但如果不是,我会使用
ExecuteCommand
。You should probably consider changing your design this doesn't sound like it will scale well, i would probably do it with a trigger if it is always required, but if not, id use
ExecuteCommand
.看看你对保罗回答的评论,我觉得我应该在这里插话。我们有几个表,需要保存该表中每个条目的历史记录。我们通过为每个创建一个单独的表来实现这一点。例如,我们可能有一个
Comment
表,然后是一个CommentArchive
表,其中包含对Comment 中的
表。CommentId
的外键引用Comment
表上的触发器可确保每次更新Comment
表中的某些字段时,“旧”版本(可通过deleted
访问)触发器中的 code> 表)被推送到CommentArchive
表。显然,这意味着每个Comment
可能存在多个CommentArchive
条目,但如果您只查找“活动”评论,则只需查看Comment
表。如果您需要有关评论历史记录的信息,您可以轻松使用 LINQ to SQL 从您感兴趣的评论跳转到引用它的 CommentArchives。由于我们在上面示例中使用的触发器每次更新时仅将单个值插入到存档表中,因此它们运行速度非常快,并且我们获得了良好的性能。最近我们遇到了一些问题,我尝试让触发器变得更复杂,但只有 15 个并发事务时我们就开始出现死锁。因此,我们的教训是,您应该使这些触发器变得简单,并让它们接触尽可能少的表中的尽可能少的行。
Looking at your comment on Paul's answer, I feel like I should chime in here. We have a few tables where we need to keep a history of each entry in that table. We implement this by creating a separate table for each. For example, we may have a
Comment
table, and then aCommentArchive
table with a foreign key reference to theCommentId
in theComment
table.A trigger on the
Comment
table ensures that each time certain fields in theComment
table are updated, the "old" version (which is accessible via thedeleted
table in the trigger) gets pushed to theCommentArchive
table. Obviously, this means severalCommentArchive
entries may exist for eachComment
, but if you're only looking for the "active" comments, you just look in theComment
table. And if you need information about the history of a comment, you can easily use LINQ to SQL to jump from the Comment you're interested in to the CommentArchives that reference it.Because the triggers we use in the above example only insert a single value into the Archive table for each update, they run very quickly and we get good performance. We had issues recently where I tried making the triggers more complex and we started getting dead-locks with as few as 15 concurrent transactions. So the lesson is that you should make these triggers simple, and make them touch as few rows in as few tables as possible.