Entity Framework 4 DB-First Dependency Injection?

孤者浪人 提交于 2019-12-21 05:25:09

问题


I prefer creating my own DB, setting up indexes, unique constraints etc. Generating the domain model from the database is a cinch with the edmx Entity Framework designer.

Now I'm interested in setting up some repositories an using Dependency Injection. I've looked at some articles and posts on StackOverflow and seem to focus on the code-first approach. It is pretty slick how you can create a generic repository to handle the CRUD and use Dependency Injection to choose the implementation details.

I'd like to do the same thing, but it seems that the domain model generated by the edmx process inherits concrete classes instead of implementing interfaces (ObjectContext/ObjectSet as opposed to IObjectContext/IObjectSet).

Does anyone have any resources they can point me to on how I might use Dependency Injection when utilizing the db-first/code generation technique?


回答1:


Maybe I am misunderstanding your question, but the fact that the EDMX generates code that inherits from ObjectContext doesn't stop you from using dependency injection. It sounds like you are worried about not being able to inject your ObjectSet into your Repository, but that isn't quite the way it is designed to be used.

With a generic repository pattern such as the one found here, the IRepository interface is the thing that you inject into your ViewModels/Controllers/Whatever.

So, you don't inject an IObjectContext or IObjectSet into your Repository; instead, you inject your IRepsoitory into your classes that need it, and you provide an implementation of the IRepository interface that uses your ObjectSet. You can then mock your IRepository interface for testing, or switch to a completely different concrete repository implementation, without affecting any of your other code.

We are currently doing this exact same thing with EF4 DB-first and the repository pattern I linked above, and it is working quite nicely.




回答2:


I myself have been researching for an answer for this question and I got this solution: DBContext generator tutorial to generate a POCO model after creating the Entity model with database first.

After that the implementation is pretty straightforward as this resembles very much with CodeFirst Repository&DI patterns Repository & DI (IoC) patterns



来源:https://stackoverflow.com/questions/8448791/entity-framework-4-db-first-dependency-injection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!