This is in continuation of two ongoing problems I'm facing: Problems trying to attach a new EF4 entity to ObjectContext while its entity collection entities are already attached and EF4.0 - Is there a way to see what entities are attached to what ObjectContext during debugging? I'm using this space to ask another somewhat complicated question, and I don't want to make a huge, ultra long question out of my other threads.
So, a quick rundown:
I have incoming form data which is bound to a DTO. I want to map the DTO to an Entity (a Game entity). The wrinkle is that the Game contains a EntityCollection which I must create and Add() to the Game based on a int[] in the DTO (each integer represents the ID of a Platform). And, naturally, EF4 is choking in part because it's a many-to-many relationship, but also, I think, because there's some shenanigans going on with how many ObjectContext objects are in play. I keep getting an exception claiming I can't add my retrieved Platform entities to my new Game entity because they belong to two different ObjectContexts. I can't see how that is possible given my current set up, but I'm not sure what else the problem could be.
Okay, so I have three repositories which I inject into my controller via Ninject interface injection. I create the ObjectContexts in each like so:
public class HGGameRepository : IGameRepository
{
private HGEntities _siteDB = new HGEntities();
// rest of repo
}
The other two repositories are built the same way.
My Ninject DI code is fairly simple:
private class HandiGamerServices : NinjectModule
{
public override void Load()
{
Bind<IArticleRepository>().To<HGArticleRepository>().InRequestScope();
Bind<IGameRepository>().To<HGGameRepository>().InRequestScope();
Bind<INewsRepository>().To<HGNewsRepository>().InRequestScope();
Bind<ErrorController>().ToSelf().InRequestScope();
}
}
From what I've read, this should create these bindings once per HTTP request.
What I'd like to do is have one instance of my HGEntities object be shared among all repositories in order to ensure I have one and only one ObjectContext in play. I'm just unsure how to do it.
开发者_运维百科Is there a standard way to do this?
Here's one option:
Change your repositories to take in an interface, IHGEntities, in their constructor and hook up HGEntities into your NinjectModule the same you did with your repositories. That way, when your controllers need an instance of IArticleRepository, Ninject will either instantiate an instance of HGEntities to pass into the repositories or use the instance that is already active in the current HTTP context.
Then, inside your repository classes you can simply cast IHGEntities to HGEntities.
精彩评论