I have a pet project of mine written in php. One of jobs my code do is to load bunch of csv files and write them to MySQL table which have both autogenerated primary key and multipart unique key. I have no control and ways to check is some file already processed so unique key came handy. I insert data into table with INSERT IGNORE which silently fails when i try to insert data which already exist and everything works great as it should.
Now, I am trying to make similar project in C# 4 using LINQ To Entities but when I try to call ObjectContext.SaveChanges() method for objects from files which are already in table, UpdateException is thrown with SqlClient.SqlException as inner exception. One solution was adding Ignore Duplicate Keys = Yes to index and it kinda works but
Is there easy and elegant way to accomplish those inserts with L2E which does not involve database changes???
Another solution will be something like this:
public void SaveAll( IEnumerable<Entity> entities )
{
var ids = entities.Select(x => x.Id).ToList();
var idsToRemove = context.Entities.Where(x => ids.Contains(x.Id)).Select(x => x.Id).ToList();
var entitiesToInsert = entities.Where(x => !idsToRemove.Contains(x.Id));
foreach(var entity in entitiesToInsert)
context.Entities.AddObject(entity);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With