2

I have an IEnumerable ORDERS that I get from reading from an excel file. Then I add each row:

foreach (var item in so)
{
       context.ORDERS.AddObject(item);
}
db.SaveChanges();

Sometimes there are duplicates in the source file, and I'm not sure how to not add duplicates to the table.

4

1 回答 1

1

how to not add duplicates to the table.

Check whether the ORDERS list already contains the item or not before add it to the list. Use Any for example like this:

foreach (var item in so)
{
    //If ORDERS List doesn't contain any item with the same id 
    //or any other predicate match
    if(!context.ORDERS.Any(o => o.Id == item.Id)) //or any other property of item
       context.ORDERS.AddObject(item);
}
db.SaveChanges();
于 2012-06-24T14:29:37.307 回答