可以使用Linq在Sql和DataTable之间编写连接吗?

我有一个过程,根据时间戳从多个数据库(MySql)中提取客户信息。 我将这些数据存储到DataTable 。 数据表表示现有客户信息的更新以及新客户信息。

我想基于一个常量值, CompanyIDCustomerID删除目标数据库(SqlServer)中的任何欺骗。 所以,我认为连接会给我目标数据库中的dupes的RecordID,将List (或某些集合机制)传递给DELETE方法。

是)我有的:

 using (var context = new DataContext(SqlConnection)) { var tblSource = context.GetTable(); var dupeIDs = from currCust in tblSource join newCust in myTable.AsEnumerable() on currCust.CompanyID equals newCust.Field("CompanyID") where currCust.CustomerID.Equals(newCust.Field("CustomerID") select currCust.RecordID; } 

这显然不起作用。 我将稍微更新确切的错误消息,但这不会编译。

首先,我的连接语法是否正确我想要实现的目标?

其次,如何编写这个Linq来连接DataTable和目标SqlServer数据库?

事后想想 – 一旦我有一个dupe RecordID集合,是否有可能使用Linq来删除目标数据库中的记录?

编辑为了澄清这个过程,我有像这样的传入数据表并包含在DataSet

 Table1 CompanyID CustomerID Field1 Field2 .... 1 5 ... ... 1 15 ... ... Table2 CompanyID CustomerID Field1 Field2 .... 10 125 ... ... 10 145 ... ... 

这些都将进入一个数据库:

 Destination DB CompanyID CustomerID Field1 Field2 .... 1 5 ... ... 1 15 ... ... 1 27 ... ... 5 15 ... ... 10 125 ... ... 10 145 ... ... 11 100 ... ... 

因此,在这种情况下,我将从目标表中删除与表1和2匹配的项目。目标数据库将不断增长,因此创建CustomerID列表似乎不可行。 但是,我希望每天导入的新客户信息和更新的客户信息相对较少(数百个,可能接近1000个记录)。

如果我不能写一个连接,那么完成这个过程的其他方法是否合适? 我试图找出一些东西,因为它看起来我实际上无法混合Linq-to-Sql和Linq-to-Objects。

是否有可能以某种方式我的数据表映射到实体数据 tbl_CustomerInfo ,填充其他不可变的var,然后执行连接?

更新

这是我在这一点上所取得的成就,我得到了我期望的结果:

 using (DataContext context = new DataContext(SqlConnection) { var custInfo = context.GetTable(); string compID = ImportCust.Rows[0]["CompanyID"].ToString(); var imports = from cust in ImportCust.AsEnumerable() select cust.Field("CustomerID"); var dupes = from cust in custInfo join import in imports on cust.CustomerID equals import where cust.CompanyID == compID select cust; custInfo.DeleteOnSubmit(/* what goes here */); context.SubmitChanges(); } 

我现在的问题是, DeleteOnSubmit(...)什么? 我觉得我已经如此接近,只是被这个挫败了。

我通常在存储过程中处理所有这些以提高效率。

将标识字段添加到目标表以唯一标识记录,然后使用如下查询:

 DELETE d FROM DestinationTable d JOIN ( Select CompanyID, CustomerID, Min(UniqueID) AS FirstRecID FROM DestinationTable GROUP BY CompanyID, CustomerID) u on u.CompanyID=d.CompanyID AND u.CustomerID=d.CustomerID WHERE d.UniqueID <> u.FirstRecID 

或者,您可以创建两个List ,其中包含来自两个源的id,然后使用Intersect LINQ运算符查找公共项。

 List a = new List{1,2,3,4,5,6,8, 10}; List b = new List{1,2,99,5,6,8, 10}; var c= a.Intersect(b); //returns the items common to both lists 

这是我的工作:

 using (DataContext context = new DataContext(SqlConnection) { var custInfo = context.GetTable(); string compID = ImportCust.Rows[0]["CompanyID"].ToString(); var imports = from cust in ImportCust.AsEnumerable() select cust.Field("CustomerID"); var dupes = from import in imports join cust in custInfo on import equals cust.CustomerID where cust.CompanyID== pivnum select cust; var records = dupes.GetEnumerator(); while (records.MoveNext()) { custInfo.DeleteOnSubmit(records.Current); } context.SubmitChanges(); } 

如果有更有效的方法,我对选项感兴趣。