question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Update of owned entity fails

See original GitHub issue

If I update an owned entity a call to SaveChanges crashes with the exception below.

System.InvalidOperationException: The instance of entity type 'Person.Address#Address' cannot be tracked because another instance with the same key value for {'PersonId'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMap`1.Add(TKey key, InternalEntityEntry entry)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.StartTracking(InternalEntityEntry entry)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.SetEntityState(EntityState oldState, EntityState newState, Boolean acceptChanges)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.SetEntityState(EntityState entityState, Boolean acceptChanges, Boolean forceStateWhenUnknownKey)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityGraphAttacher.PaintAction(EntityEntryGraphNode node)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityEntryGraphIterator.TraverseGraph(EntityEntryGraphNode node, Func`2 handleNode)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityGraphAttacher.AttachGraph(InternalEntityEntry rootEntry, EntityState entityState, Boolean forceStateWhenUnknownKey)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.NavigationFixer.NavigationReferenceChanged(InternalEntityEntry entry, INavigation navigation, Object oldValue, Object newValue)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntryNotifier.NavigationReferenceChanged(InternalEntityEntry entry, INavigation navigation, Object oldValue, Object newValue)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.ChangeDetector.DetectNavigationChange(InternalEntityEntry entry, INavigation navigation)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.ChangeDetector.DetectChanges(InternalEntityEntry entry)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.ChangeDetector.DetectChanges(IStateManager stateManager)
   at Microsoft.EntityFrameworkCore.ChangeTracking.ChangeTracker.DetectChanges()
   at Microsoft.EntityFrameworkCore.DbContext.TryDetectChanges()
   at Microsoft.EntityFrameworkCore.DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess)
   at Microsoft.EntityFrameworkCore.DbContext.SaveChanges()
class Program
    {
        static void Main(string[] args)
        {
            try
            {
                int id;
                using (var context = new TestDbContext())
                {
                    context.Database.Migrate();

                    var result = context.Persons.Add(new Person("John Doe", new Address("SomeStreet")));
                    context.SaveChanges();
                    id = result.Entity.Id;
                }

                using (var context = new TestDbContext())
                {
                    var person = context.Find<Person>(id);

                    person.Move(new Address("OtherStreet"));

                    context.SaveChanges();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                Console.ReadLine();
            }
        }
    }

    public class TestDbContext : DbContext
    {
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer("Server=.;Database=OwnOneTest;Integrated Security=SSPI");
            base.OnConfiguring(optionsBuilder);
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Person>().OwnsOne(x => x.Address);

            base.OnModelCreating(modelBuilder);
        }

        public DbSet<Person> Persons { get; set; }
    }

    public class Person
    {
        [Obsolete("ORM constructor", true)]
        protected Person() {}

        public Person(string name, Address address)
        {
            Name = name;
            Address = address;
        }

        public int Id { get; private set; }

        public string Name { get; private set; }
        public Address Address { get; private set; }

        public void Move(Address address)
        {
            Address = address ?? throw new ArgumentNullException(nameof(address));
        }
    }

    public class Address
    {
        [Obsolete("ORM constructor", true)]
        protected Address() { }

        public Address(string street)
        {
            Street = street;
        }

        public string Street { get; private set; }
    }

If this is not the correct way to map DDD Entities and Value Objects, then how should I do it?

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Reactions:4
  • Comments:27 (11 by maintainers)

github_iconTop GitHub Comments

3reactions
julielermancommented, May 23, 2018

If it’s any use, I wrote an article with help from @AndriySvyryd (on the EF team) about a workaround . It’s here: https://msdn.microsoft.com/magazine/mt846463. Note that the workaround doesn’t work with InMemory, however. 😦

3reactions
andriysavincommented, May 23, 2018

@ahmedtolba1984 nope, all hope to MS guys 😃

Read more comments on GitHub >

github_iconTop Results From Across the Web

Update owned entity EF Core 5
Address is owned entity type, hence Student.Address property by EF Core ... To force updating just some properties of the Student.
Read more >
Owned Entity Types - EF Core
Owned entities are essentially a part of the owner and cannot exist without it, they are conceptually similar to aggregates. This means that...
Read more >
Error In Update Record (The instance of entity type 'x' ...
I have this error when update record in RoleRepository. cs. The instance of entity type 'ApplicationRole' cannot be tracked because another ...
Read more >
Modifying data via the DbContext
The approach that you adopt to update/modify entities depends on whether the context is currently tracking the entity being modified or not.
Read more >
Fail to update Entity with nested value objects-entityframework ...
According to this EF Core GitHub ticket you have to update the child/nested/owned type properties directly for it to track properly. This was...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found