确定源的DataContext的LINQ到SQL查询DataContext、LINQ、SQL

2023-09-04 00:44:48 作者:魂戒魔王

在我的应用我有几个DataContexts连接到不同的模式不同的数据库。在自定义用户控制我显示该查询的结果,并让用户进行编辑,并且当用户编辑数据欲保持变更到数据库。要做到这一点,我需要一个参考源DataContext的(或至少是源DataContext的类型),所以我可以做一个 DataContext.SubmitChanges();

有没有什么办法来确定哪些DataContext的查询从何而来?该DataQuery类本身被标记为内部的,所以不诉诸丑陋的反思黑客无法访问其上下文属性,所以我在寻找一个更清洁的方式。

有(几个)解决此问题的方式,沿着参考源的DataContext比​​如传球,但我想必须有一个简单的方法来做到这一点。

编辑: 下面code的作品,但它的丑陋:

 字段信息contextField = query.GetType()getfield命令(背景,BindingFlags.Instance | BindingFlags.NonPublic可)。
如果(查询!= NULL)
{
  queryContext = contextField.GetValue(值)作为DataContext的;
}
 
在visual studio中创建SQL Server数据库用于LinqDataSource配置数据源

解决方案

我认为你将不得不简单地传递在DataContext到code(手动)。对不起。

In my application I have several DataContexts that connects to different databases with different schemas. In a custom user control I display the results of the query and let the user edit them, and when the user edits the data I want to persist the changes to the database. To do that I need a reference to the source DataContext (or at least the source datacontext type) so I can do a DataContext.SubmitChanges();

Is there any way to determine which DataContext a query comes from? The DataQuery class itself is marked as internal, so I can't access its context property without resorting to ugly reflection hacks, so I'm looking for a cleaner approach.

There are (several) ways around this problem, passing along a reference to the source DataContext for instance, but I imagine there must be a simpler way to do this.

Edit: The following code works, but it's ugly:

FieldInfo contextField = query.GetType().GetField("context", BindingFlags.Instance | BindingFlags.NonPublic);
if (query != null)
{
  queryContext = contextField.GetValue(value) as DataContext;
}

解决方案

I think you're going to have to simply pass the DataContext to the code (manually). Sorry.