0

I am trying to insert multiple rows using the following code. SaveChanges() works for the first record but if fails when it tries the next one. My guess is that each time it is trying to insert all records. Not sure if this is correct or not, and if it is correct how can I change the code to make it correct. Following is my code: Contrroller:

foreach(var m in pms)
            {
                _pmService.AddPms(m);
            }

And in _pmService.AddPms:

_pmRepository.Add(pm);
_pmRepository.SaveChanges();

_pmRepository.Add (actually this is from BaseRepository and pmRepository extends this Base)

 _ctx.Set<T>().Add(entity);

Finally, here is my SaveChanges() (again this is also from BaseRepostiroy)

    _ctx.ChangeTracker.DetectChanges();
    return _ctx.SaveChanges(); 

So in controller, I am looping through each entry, and then calling Add. The Add in service is calls Add in BaseRepository and then it does the SaveChanges(). For first record it works without any issues but 2nd record onwards it fails. And following is the error:

"Saving or accepting changes failed because more than one entity of type XXXXXXXXXXXXX have the same primary key value. Ensure that explicitly set primary key values are unique. Ensure that database-generated primary keys are configured correctly in the database and in the Entity Framework model. Use the Entity Designer for Database First/Model First configuration. Use the 'HasDatabaseGeneratedOption\" fluent API or 'DatabaseGeneratedAttribute' for Code First configuration."

And I am using DatabaseFirst approach.

Ram V
  • 684
  • 1
  • 8
  • 18
  • I think your issue is similar to http://stackoverflow.com/questions/22489118/the-right-way-to-insert-multiple-records-to-a-table-using-linq-to-entities – sundeep Jul 18 '15 at 02:18

1 Answers1

0

I found the answer it is with StoreGeneratedPattern. I had to set this Identity in edmx file for the primary key field and it worked.

StoreGeneratedPattern="Identity"
Ram V
  • 684
  • 1
  • 8
  • 18