Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ObjectContext.SaveChanges and Duplicate PRIMARY Key

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

  • It is change on server instead on client
  • OptimisticConcurrencyException is thrown on update with existing index

Is there easy and elegant way to accomplish those inserts with L2E which does not involve database changes???

like image 864
darko99 Avatar asked Dec 14 '25 14:12

darko99


1 Answers

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);
}
like image 88
Ivo Avatar answered Dec 16 '25 07:12

Ivo