0

I am having an issue saving my objects with entity framework. I am using Webforms and here is how my code is setup:

My AppSettings has an AddressId. I prefer to save them separately. So AppSettings get saved by AppSettingRepo and the Address gets saved by AddressRepo.

CODEBEHIND:

    AppSetting appSettings = AdminService.GetAppSettings();
    //SET APP SETTING PROPERTIES

    Address address = AdminService.GetAddressById(appSettings.AddressId);
    //SET APP SETTING ADDRESS PROPERTIES

    AdminService.SaveAppSettings(appSettings);
    AdminService.SaveAddress(address);

AppSetting Repository(my AddressRepository looks exactly the same):

    public static void Save(Data.AppSetting appSettings)
    {
        using (var context = new AppContext())
        {
            if (appSettings.Id == 0)
            {
                context.AppSettings.Add(appSettings);
            }
            else
            {
                context.AppSettings.Attach(appSettings);
                context.Entry(appSettings).State = EntityState.Modified;
                appSettings.DateModified = DateTime.Now;
            }
            context.SaveChanges();
        }
    }

THE ERROR:

An exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll but was not handled in user code

Additional information: Attaching an entity of type 'App.Data.AppSetting' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values.

ocuenca
  • 38,548
  • 11
  • 89
  • 102
JTunney
  • 914
  • 1
  • 15
  • 46
  • You might have a look at my answer on [ASP.NET MVC - Attaching an entity of type 'MODELNAME' failed because another entity of the same type already has the same primary key value](http://stackoverflow.com/questions/23201907/asp-net-mvc-attaching-an-entity-of-type-modelname-failed-because-another-ent/39557606#39557606). – Murat Yıldız Sep 18 '16 at 12:31

1 Answers1

0

I figured it out I was using AutoMapper and mapping in the wrong direction.

No need for both the Attach and setting the State.

When creating:
context.Entry(object).State = EntityState.Added;

When updating:
context.Entry(object).State = EntityState.Modified;

JTunney
  • 914
  • 1
  • 15
  • 46