last day (14 days later) » 

11:36 AM
0
Q: Entity Famework core - The instance of entity type cannot be tracked because another instance of this type with the same key is already being tracked

gvkAm currently trying out my hand in .net core and EF core. I have the following code to update the data protected void Update(T entity, bool saveChanges = true) { _context.Set<T>().Attach(entity); _context.Entry(entity).State = EntityState.Modified; if (saveChanges) _context.SaveChan...

 
are you using a BlogRepository? can you show us the like where you tell the service to inject the repository in the startup?
 
gvk
services.AddScoped<BlogRepository, BlogRepository>(); this is how BlogRepository is used in startup
 
that exception means that you are trying to attach two entity instances that have the same key to a context. This occurs when a singleton instance of a repository is injected at startup. Can you upload your project code and share it?
 
gvk
The project is available at github.com/gvijayakumar-16/SampleProject2
 
Your Service Provider is static and so it is a singleton in fact. github.com/aspnet/EntityFramework/issues/2652
 
gvk
11:36 AM
@alessalessio any suggestions on how to overcome that without doing constructor injection
 
i don't think it is a problem of the DI
i would do things much easier.
1) don't use an abstract class as your Repository<Blog>. Use an Interface
and inject it in services.AddScoped<IRepository<Blog>>, BlogRepository>()
your main problem is that static class . i would get rid of it
 
gvk
services.AddScoped<IRepository<Blog>>, BlogRepository>()
if I use the above line, I need to be creating a separate scope for each model I add right?
 
yes. one repository per model. which is actually the purpose of having repositories
ex.: services.AddScoped<IRepository<Post>>, PostRepository>()
if you don't want to do this
go on with your servicemanager, but avoid it being static
 
gvk
ok, thank you.. I will try it
and on a totally different topic, any suggestion on what can be improved on the layers I have used
 
11:53 AM
sorry i haven't gone through them in detail.
I ll add an aswer to your question, i d appreciate if you can accept it as an aswer
 
gvk
sure will do
 
cheers
 

last day (14 days later) »