MVCDatabaseInitializer
MVCDatabaseInitializer

Reputation: 123

Decoupling an ASP.NET MVC application from Entity Framework

If I have this project structure

Isn't that supposed to allow me to prevent adding a reference to EntityFramework from Foo.Web?

How can I call System.Data.Entity.Database.SetInitializer() from my global.asax.cs without adding the EntityFramework reference?

Upvotes: 4

Views: 919

Answers (3)

Tomas Aschan
Tomas Aschan

Reputation: 60674

Why do you want to?

The reason you're doing this uncoupling is (I assume) to enable you to switch out the data tier at a later point, without having to modify anything in the Web project, and as little as possible in the Business project. To accomplish this, you should make sure that all your classes work against interfaces, rather than against concrete implementations.

In your example, you should probably define a Repository interface of some sort, which includes an Initialize() method. You then create a class (perhaps your specialized DbContext) implement the interface, and you work against that. In the Initialize() method on your repository, you call Database.SetInitializer() and thus you never have to reference System.Data.Entity in either the web or business projects.

Upvotes: 3

Omar
Omar

Reputation: 40202

What you can do is create a InitializeDatabase() function in your Foo.Business project which in-turn calls System.Data.Entity.Database.SetInitializer(). You can then call InitializeDatabase() from your Foo.Web project which already has a reference to Foo.Business

Upvotes: 2

Steve Mallory
Steve Mallory

Reputation: 4283

Nope. If Foo.Web needs classes in EntityFramework, it will have to reference it. References don't cascade between projects.

Upvotes: 2

Related Questions