c# - Using DI but getting : An entity object cannot be referenced by multiple instances of IEntityChangeTracker but

问题描述:

None of the questions I have reviewed on this subject are using IOC whereas I am so I don't understand why I am getting this error. As I understand it, if I only have one instance of my context, I shouldn't be receiving this error. This is a broken down version of my setup.

This doesn't have anything to do with your DI container. That error means that somewhere in your context, you have created two DbSet properties that both point to the same entity.

Since the advent of ASP.NET Identity, the most common cause of this is individuals trying to add their own DbSet<ApplicationUser> property, when IdentityDbContext<ApplicationUser> already has one, which your application's context inherits.

Not sure if that's your problem, because you haven't specified what version of MVC you're using or posted the contents of your context. That should give you enough to look into the issue, though.

网友答案:

I've found the reason for this. It was down the the caching I am performing on the _categoryService. My Get() method looks like this:

Basically, because I am not detaching my entities from the context they were in when they were cached, I then get the cached versions in a later request and they don't have the same context. So although it's not the DI at fault, it is because the context doesn't match between the entities.