Danny Tuppeny
Danny Tuppeny

Reputation: 42453

In ASP.NET MVC, where is the "best practice" place (folder) to put my Entity-Framework DataContext class?

I've seen a few projects with Entity Framework DataContext classes in the "Models" folder, but since it's not really a model, this doesn't feel right.

Currently my DataContext (along with the IDatabaseInitializer class) live in the root of my project, but that bugs me too.

Is there a common/best practice for this, or should I just leave them in the root or a folder called Data or something?

Upvotes: 18

Views: 14345

Answers (6)

RPM1984
RPM1984

Reputation: 73133

Arguably it is the model, since it what maintains the state of your application. That's why people put it there.

If you're a good boy and use an abstraction/repository layer - it should go there.

If your Controllers are talking directly to the EF context (bad idea), then put it in the models folder - no need to physically hide something you're not logically abstracting.

Upvotes: 11

Vince Ashby-Smith
Vince Ashby-Smith

Reputation: 1192

Just my thoughts on this; for any classes that are associated with Entity Framework, such as a DataContext class or a Base class, we put these in a DataFramework folder. As in theory whilst they extend EntityFramework in this context, there is no reason why they couldn't extend another database framework such as nHibernate.

Upvotes: 1

ZippyV
ZippyV

Reputation: 13068

It doesn't matter. I put it in the Models folder because that's where all the database stuff goes into.

Upvotes: 5

Safran Ali
Safran Ali

Reputation: 4497

I'll say its best practice to put it in model, as it is describe by MVC model and as I have been working on MVC for last 3 months I am very much into favour for this ... plus it gives you much flexibility when calling the EM classes ...

Upvotes: 3

Kuvalda.Spb.Ru
Kuvalda.Spb.Ru

Reputation: 443

Create different project with our data repository, add project to solution and reference it where need. Repository pattern make benefits to testing and changing your data layer in feature as need.

See http://www.asp.net/entity-framework/tutorials/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application

Upvotes: 2

James McCormack
James McCormack

Reputation: 9964

At other places I've worked, VS Solutions were split into 3 projects:

  • Presentation (MVC Site)
  • Service (Business logic classes inc. POCO entities)
  • Repository (Data access inc. EF Data Contexts)

Upvotes: 3

Related Questions