Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework 4 DB-First Dependency Injection?

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?

like image 524
Sam Avatar asked Dec 21 '22 05:12

Sam


2 Answers

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.

like image 164
Marty Avatar answered Jan 07 '23 17:01

Marty


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

like image 37
MariaMadalina Avatar answered Jan 07 '23 18:01

MariaMadalina