1

I am trying to insert by using EF and pasing all parameters but still for some reason I am getting Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries. error.

I looked into Solution for: Store update, insert, or delete statement affected an unexpected number of rows (0) and dbcontext does not contain a definition for 'Refresh' but still I am getting the error.

I tried following approaches:

foreach (var mainItemDeliveryTag in mainItemDeliveryTagList)
{
    try
    {   //Option-1
        var mainItemTag = DataContext.Set<MainItemDeliveryTag>();
        mainItemTag.Add(new MainItemDeliveryTag { MainItemID = mainItemId, DeliveryProviderTagID = mainItemDeliveryTag.DeliveryProviderTagID, IsDeliveryTagSelected = mainItemDeliveryTag.IsDeliveryTagSelected });

        //Option-2
        var mainItemDeliveryTagObj = new MainItemDeliveryTag()
        {
            MainItemID = mainItemId,
            DeliveryProviderTagID = mainItemDeliveryTag.DeliveryProviderTagID,
            IsDeliveryTagSelected = mainItemDeliveryTag.IsDeliveryTagSelected,
        };
        DataContext.MainItemDeliveryTag.Add(mainItemDeliveryTagObj);

        //Option-3
        DataContext.Entry(mainItemDeliveryTag).State = System.Data.Entity.EntityState.Added;

        DataContext.SaveChanges();
    }
    catch (OptimisticConcurrencyException)
    {
        var ctx = ((IObjectContextAdapter)DataContext).ObjectContext;
        ctx.Refresh(RefreshMode.ClientWins, mainItemDeliveryTag);
        DataContext.SaveChanges();
    }
}

What am I missing here?

Community
  • 1
  • 1
GThree
  • 2,708
  • 7
  • 34
  • 67
  • First of all: use Option-2 but move SaveChanges() invoke outside the loop. What is the mainItemId? Is it primary key for this table? Could tell us where you create your DataContext? – Marcin Iwanowski Mar 30 '16 at 18:33
  • MainItemId is not primary key. It is just to associate some value with id – GThree Mar 30 '16 at 18:51
  • @MarcinIwanowski I didn't have any auto increment column in my table so EF was not able to do insert records. I added one column with auto increment and run the same code. It started working. – GThree Mar 30 '16 at 19:00

1 Answers1

0

Previously my table didn't have any column with auto increment value. I added new column with auto increment and now I am able to insert records.

Old Table Structure:

enter image description here

New Table Structure:

enter image description here

GThree
  • 2,708
  • 7
  • 34
  • 67