ObjectContext.SaveChanges and Duplicate PRIMARY Key

I have my favorite project written in php. One of my tasks is to load a bunch of csv files and write them to a MySQL table, which have both an auto-generated primary key and a multi-purpose unique key. I have no control and verification methods - this is an already processed file, so a unique key was at hand. I insert data into a table with help INSERT IGNOREthat silently fails when I try to insert data that already exists, and everything works fine, as it should.

Now I'm trying to make a similar project in C # 4 using LINQ To Entities, but when I try to call a method ObjectContext.SaveChanges()for objects from files that are already in the table, it UpdateExceptionis created with SqlClient.SqlExceptionan internal exception. One solution was to add Ignore Duplicate Keys = Yesto the index, and it kind of works, but

  • This is a change on the server instead of the client
  • OptimisticConcurrencyException thrown when updating using an existing index

Is there a simple and elegant way to perform these inserts with L2E that are not related to database changes?

+3
source share
1 answer

Another solution would 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);
}
+1
source

Source: https://habr.com/ru/post/1796652/


All Articles