C# / LINQ(?) - 连接两个数据表(无需 SQL!)
我有两个数据表(在 SQLS DB 内)具有关系(我们将它们称为 dtStock 和 dtSpec,其中 dtSpec.ItemTypeID = dtStock.ID)。我分别从数据库中提取它们(使用 SqlClient),以便我可以使用 CommandBuilders 更新它们。
我有一个控件想要查看单个数据表(dtJob)。
如何加入它们,以便当我使用控件更新 dtJob 时,dtSpec 和 dtStock 也会更新?我猜这将涉及 LINQ...
这听起来应该是一件非常简单的事情,但我发现的大多数示例似乎都是将数据复制到新表而不是引用原始数据,或者需要大量代码来完成(例如重写 CopyToDataTable 方法来处理连接)。也许我的 Google-fu 只是垃圾。
提前致谢
I have two Datatables that (inside the SQLS DB) have a relationship (let's call them dtStock and dtSpec, where dtSpec.ItemTypeID = dtStock.ID). I am pulling these from the DB separately (using SqlClient) so I can update them both with CommandBuilders.
I have a control that wants to see a single Datatable (dtJob).
How do I join them so that when I update dtJob using the control, dtSpec and dtStock get updated as well? I'm guessing this will involve LINQ...
This sounds like it should be a pretty simple thing to do, but most of the examples I've found seem to COPY the data to a new table rather than refer to the original data, or require a lot of code to accomplish (e.g. rewriting the CopyToDataTable method to deal with joins). Maybe my Google-fu is just rubbish.
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
假设 dtJob 的架构 DataTable 是您可能需要查看 DataTable.Merge 方法将更改从
dtJob
传播到其他两个表。下面是一个示例:
请注意,在此示例中我使用了命名参数 ,仅在 C# 4.0 中可用,以便使方法调用更具可读性。
下面是一个更完整的示例:
相关资源:
Assuming that the schema of the
dtJob
DataTable is the sum of thedtStock
anddtSpec
schemas you might want to look at the DataTable.Merge method to propagate the changes fromdtJob
to the two other tables.Here's an example:
Note that in this sample I've used named arguments, which are only available in C# 4.0, in order to make the method call more readable.
Here's a more complete example:
Related resources:
最后,我放弃了这个数据表的想法,并选择了一个列表(即使需要更多的代码)——经过一番思考后,我发现连接两个数据表并不是我真正想做的,事情有点复杂。不过还是谢谢你的帮助。
In the end I canned this DataTable idea and went with a List (even with the higher quantity of code required) - after some thought I discovered that joining two Datatables isn't what I really wanted to do anyway, things were somewhat more complex. Thanks for the help though.