views:

49

answers:

2

I am new to Entity Framework 4, and I am wondering, what's the best way to organize my data layer--the code that accesses EF4?

At this point, my data layer is set up like this:

  • DataStore class: Holds a reference to the EF4 ObjectContext, and contains methods to open, close, and persist the ObjectContext to storage.

  • Repository classes: One class for each entity, with methods to create, fetch, and delete entity objects.

Is there a better way to organize this functionality for EF4? I've looked for articles/blogs on the subject, but I'm not finding much. Any suggestions? Thanks for your help.

+1  A: 

I prefer the repository classes for each entity type (I know them as DataMapper). One class for all queries easily becomes too monolithic hard to maintain.

Florian Reischl
I think we are in agreement on that point. I use a separate Repositorey class for each 'root' entity type; i.e., the types I will execute queries on. +1 for the reference to DataMapper--thanks!
David Veeneman
+1  A: 

I use a generic repository for Entity Framework that makes access very easy. No need to write a separate repository for each entity, just:

MyDataContext ctx = new MyDataContext();
Repository<MyEntity, MyDataContext > myEntityRep = new Repository<MyEntity, MyDataContext>(ctx);
myEntityRep.Add(new MyEntity() {//property settings});

This repository totally abstracts the Entity model, allowing for creating, modifying, and deleting entities.

Dave Swersky
That's a good point. I do use a generic Repository class as a base class for my Repositories. It eliminates most of the plumbing code needed for Repository classes. The only code I need is for queries that are unique to a particular entity.
David Veeneman
Okay, it sounds like I am using a reasonable approach. Selected this answer because of the code included. Any other suggestions very welcome.
David Veeneman