问题描述
已搜查蚂蚁在这个论坛上测试了许多例子,但不能得到完全的工作方法。
Have searched ant tested many examples in this forum but can't get a fully working method.
我使用LINQ to批量插入实体类的列表( RemoteReadings)。
I am using linq to bulk insert a list of entity classes (RemoteReadings).
由于唯一约束我需要过滤掉已经插入任何项目。
Due to unique constraints I need to filter out any items already inserted.
Uniqiuness由2列meterid和RemoteReadings表日期时间。
Uniqiuness is composed of 2 columns meterid and datetime in RemoteReadings table.
// approx 5000 records (I need to do this in batches of 2000 due to a
// constraint in L2S,but can do this after get this working)
List<RemoteReading> lst = createListFromCSV();
// Option 1:
// This does not work as am comparing memory list to db list. I need to use contains() method.
// Actually am trying to accomplish this infollowing examples.
List<RemoteReading> myLst = (from ri in db.RemoteReadings
from l in lst
where l.meterid = ri.meterid
&& l.date = r.date
select ri).ToList();
////
// Option2:
// Get the list from DB that are in memory lst
List<RemoteReading> myLst = (from ri in db.RemoteReadings
where
// where in this list by comparing meaterid and datemeaured
(from l in lst
select
/// help here !
///
select ri).ToList<RemoteInterconnectorReading>();
// Option3:
// Get the list from lst that are not in database
// I am bit confused here !
// Tried also to remove from list any duplicates:
List<RemoteReading> result = List<RemoteReading>)myLst.Except(lst).ToList<RemoteReading>();
// Ultimately
db.RemoteReading.InsertAllOnSubmit(result);
db.submitChanges();
任何帮助吗?
Any help please?
推荐答案
由于EF限制,我们无法与内存中的列表加入DB查询。此外,包含
只能用原始的列表中使用。所以我们需要做一些努力,找到两列的重复
Due to limitations in EF, we can't join DB query with in-memory list. Also, Contains
can only be used with primitive list. So we need to make some efforts to find the duplicates on two columns.
var newItems = createListFromCSV();
var meterIds = newItems.Select(n=> n.meterid).Distinct().ToList();
var dates = newItems.Select(n=> n.date).Distinct().ToList();
var probableMatches = (from ri in db.RemoteReadings
where (meterIds.Contains(ri.meterids)
|| dates.Contains(ri.date)
select new {ri.merterid, ri.date}).ToList();
var duplicates = (from existingRi in probaleMatches
join newRi in newItems
on new {existingRi.meterid, existingRi.date}
equals {newRi.meterid, newRi.date}
select newRi).ToList();
var insertList = newItems.Except(duplicates).ToList();
db.RemoteReadings.Insert(insertList); // or whatever
这篇关于C#筛选器列表中删除任何双宾语的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!