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.