0

I am inserting some objects into the database, but getting the following errors:

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

Additional information: An entity object cannot be referenced by multiple instances of IEntityChangeTracker.

I have tried to research and find the issue, but couldn't find proper way of resolving and understanding the issue. Any help is appreciated.

Here is small source part that causes the error:

SysUsers User = GetUser()
foreach (int country in data.countries) {
        foreach (int street in data.streets)
        {
            BrowsedData tempBrowsed = new BrowsedData();
            MapInfo tempInformation = WorldInformationController.FindInformation(country, street);
            tempBrowsed.Information = tempInformation;
            tempBrowsed.User = User;
            tempBrowsed.UpdatedBy = User;
            tempBrowsed.sDateTime = data.IndividualFiscalYearEnds
                                .Where(a => a.C_ID == country)
                                .Select(a => a.LastDate).FirstOrDefault();
            this.Database.BrowsedData.Add(tempBrowsed);
            this.Database.SaveChanges();
        }
    }

The error denotes to this line: this.Database.BrowsedData.Add(tempBrowsed);

JCaptain
  • 3
  • 1
  • 7
  • Try `tempBrowser.sDateTime = DateTime.Parse(data.IndividualFiscalYearEnds.Where(a => a.C_ID == country).Select(a => a.LastDate).FirstOrDefault()?.ToString())` – Vidmantas Blazevicius Feb 09 '18 at 16:53
  • As far as I know "?" cannot be applied to DateTIme. – JCaptain Feb 09 '18 at 17:14
  • Yeah, you are right, unless it nullable `DateTime?` – Vidmantas Blazevicius Feb 09 '18 at 17:22
  • It looks like tempBrowsed.Information = tempInformation; is the problem, it may be on a different context can you assign the id instead – Petrus Prinsloo Feb 09 '18 at 17:32
  • What does you DbContext management look like? If you are using mvc are you creating the context once at BeginRequest and passing it around to all your controllers or using a IoC container that instantiates it with a scope of web request? – Fran Feb 09 '18 at 17:49

1 Answers1

0

you are trying to attach an entity to your context but its already attached to another one.

have you checked this https://stackoverflow.com/a/10194299/1481690

Am assuming the same issue

BrowsedData and MapInfo is not using the same context instance

This is also another answer in same thread which might help your case https://stackoverflow.com/a/27860667/1481690

Peru
  • 2,871
  • 5
  • 37
  • 66