1

I am getting an error that says

Attaching an entity of type 'Application.Models.DatabaseModels.Bar' failed because another entity of the same type already has the same primary key value.

I've seen this error before and know that it is occurring because I am trying to set the state of an instance of Bar to modified, when the context is already tracking an instance that has the same id. What is interesting to me is the situation that is causing Barto be tracked before I try and set the state.

Below are two blocks of code that are identical in every way except for the addition of one line in the second block. The first function will run correctly, changing the state of foo.PrimaryBar to modified, whereas the second function will throw the error.

This Works Fine:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit(ViewModel viewModel)
{
    Foo foo = await _context.Foos.AsNoTracking().FirstOrDefaultAsync(f => f.Id == viewModel.FooId);
    Foo.Primary.Bar = _context.Bars.AsNoTracking().First(c => c.Id == viewModel.PrimaryBarId);

    _context.SetModified(foo.Primary);

    //code continues
}

This Throws An Error:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit(ViewModel viewModel)
{
    Foo foo = await _context.Foos.AsNoTracking().FirstOrDefaultAsync(f => f.Id == viewModel.FooId);
    Foo.Primary.Bar = _context.Bars.AsNoTracking().First(c => c.Id == viewModel.PrimaryBarId);

    //this appears to add the Bars in Foo to the context
    var test = foo.Bars.Where(c => c.Id != foo.Primary.Bar.Id);

    //this is where the error occurs now
    _context.SetModified(foo.Primary);

    //code continues
}

To give context to the situation:

Database Models

public class Foo
{
    public int Id { get; set; }

    [ForeignKey("Primary")]
    public int? PrimaryId { get; set; }
    public virtual Primary Primary { get; set; }

    public virtual List<Bar> Bars { get; set; }
}

public class Bar
{
    public int Id { get; set; }

    [ForeignKey("Foo")]
    public int? FooId { get; set; }
    public virtual Foo Foo { get; set; }
}

public class Primary
{
    [Key, ForeignKey("Foo")]
    public int FooId { get; set; }
    public virtual Foo Foo { get; set; }

    [ForeignKey("Bar")]
    public int? BarId { get; set; }
    public virtual Bar Bar { get; set; }
}

View Model

public class ViewModel
{
    public int FooId { get; set; }
    public int? PrimaryBarId { get; set; }
}

Context

public class AppDbContext : DbContext
{
    public virtual DbSet<Foo>           Foos            { get; set; }
    public virtual DbSet<Bar>           Bars            { get; set; }
    public virtual DbSet<Primary>       PrimaryBars     { get; set; }


    public virtual void SetModified<T>(T entity) where T : class
    {
        Entry(entity).State = EntityState.Modified;
    }
}

The Question

Why does the line var test = foo.Bars.Where(c => c.Id != foo.Primary.Bar.Id); cause the Bar's to be tracked by the context even though foo itself is set to AsNoTracking()?

Am I misunderstanding what is happening here, what AsNoTracking() does, or is this a bug in Entity Framework itself?

2
  • It seems that you have enabled the Lazy Loading which is delaying the loading of Bars data, until you specifically request for it. The data is in Bars must loaded by separate query of database (which you can validate in SQL profiler). However, your question is correct that why it is fetched with Tracking even if the parent is fetched with AsNoTracking. Otherway to confirm the behavior and may be workaround for your problem is to use Eager Loading of relationship data (entityframeworktutorial.net/…). Commented Apr 29, 2018 at 5:51
  • Unfortunately, using _context.Foos.Include(f => f.Bars).etc for Eager Loading seems to do nothing to fix the issue. Interestingly enough, I discovered that the error actually disappears if I instead remove the .AsNoTracking() from my initial queries. This technically solves the issue I have - in that it removes the error - but I have no clue right now as to why it works or even if it is doing what I actually want it to.
    – Chris
    Commented Apr 30, 2018 at 16:27

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.