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.

EF7 beta6: Error saving multiple entities

See original GitHub issue

I am creating an API using ASP.NET5 and Entity Framework 7.0.0-beta 6, and when I try to execute various updates in several requests, I get this Exception:

‘Company’ cannot be tracked because another instance of this type with the same key is already being tracked. For new entities consider using an IIdentityGenerator to generate unique key values.

This is my code:

public class MrBellhopContext : DbContext
{

    public DbSet<Company> Company { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Company>(entity =>
        {
            entity.Key(c => c.CompanyId);

            entity.Index(c => c.Name);

            entity.Property(c => c.CompanyId).ValueGeneratedOnAdd();
        });

        modelBuilder.UseSqlServerIdentityColumns();

        base.OnModelCreating(modelBuilder);
    }

}


public class Company
{

    public int CompanyId { get; set; }

    public string Name { get; set; }

    public string Description { get; set; }

    public string Phone { get; set; }

    public string Email { get; set; }

    public short StatusId { get; set; }

}


public class CompanyRepository : ICompanyRepository
{

    MrBellhopContext _dbcontext;


    public async Task UpdateAsync(Company company)
    {
        _dbcontext.Update(company);
        await _dbcontext.SaveChangesAsync();
    }
}



[Route("api/[controller]")]
public class CompanyController : Controller
{


    [HttpPut]
    public async void UpdateAsync([FromBody] Company company)
    {
        if ((!ModelState.IsValid) || (company == null))
        {
            Context.Response.StatusCode = 400;
            return;
        }
        else
        {
            await _repository.UpdateAsync(company);
        }
    }

}

I have tried to solve it by removing ValueGeneratedOnAdd(), UseSqlServerIdentityColumns() or changing the mapping, but if I try to update several entities in several requests, I get the Exception:

First req: Update CompanyId 8 First req: Update CompanyId 9 !! ERROR

Does anyone know how to solve this issue?

Issue Analytics

  • State:closed
  • Created 8 years ago
  • Comments:19 (7 by maintainers)

github_iconTop GitHub Comments

2reactions
rowanmillercommented, Jul 30, 2015

@unairoldan that exception means that you are trying to attach two entity instances that have the same key to a context. This isn’t supported in EF. There can only be one entity instance with a given key per context.

This is occurring because you have added a singleton instance of your repository:

services.AddSingleton<Data.Interfaces.Company.ICompanyRepository,Data.Repositories.Company.CompanyRepository>(); 

This means that all requests are sharing a single instance of the repository. You should reduce this to Scoped, so that you have a single repository instance per request. Aside from avoiding the issue you are hitting, it will also ensure you don’t end up with a gigantic context instance tracking all the data from your database in memory.

1reaction
gollapudiramyakcommented, Feb 12, 2016

Thank you for your quick reply. How about using .AsNoTracking for all Get operations. like below

context.User..AsNoTracking()
//To Get the User
MyDataBaseContext.context.Attach(userobject);
MyDataBaseContext.context.SaveChanges();
// To Update the User
 MyDataBaseContext.context.User.Add(userobject );
 DatabaseContext.context.SaveChanges();
//To Insert a new User

Reason for going for single ton datacontext is - don’t want to open the connection for each operation from entities. Example like below for 2 entities. We have about 90 entities which are there in my MyDbontext.

using(MyDbContext db= new MyDbContext(connectionString))//open connecion
{
return db.Users;
}//closes connection
using(MyDbContext db= new MyDbContext(connectionString))//open connecion
{
return db.Person;
}//closes connection
Read more comments on GitHub >

github_iconTop Results From Across the Web

EF7 beta6: Error saving multiple entities
EF7 beta6: Error saving multiple entities · Have tried to add the [Key] attribute to the primary key property, which is in your...
Read more >
EF7 beta6: Error saving multiple entities · Issue #2652
I am creating an API using ASP.NET5 and Entity Framework 7.0.0-beta 6, and when I try to execute various updates in several requests, ......
Read more >
[Solved]-EF7 beta6: Error saving multiple entities-entityframework core
This means that all requests are sharing a single instance of the repository. You should reduce this to Scoped, so that you have...
Read more >
Can we get concurrency errors for multiple entities in EF ...
What happens if you try to save an object graph, and more than one entity in the graph has been updated since you...
Read more >
Saving Related Data - EF Core
Information on saving graphs of related entities and managing relationships in Entity Framework Core.
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