2

I'm working on an ASP.NET MVC project. In my solution I have the following projects: BlogApp.Web (ASP.NET MVC app), BlogApp.Data (Class Library)

I'm wondering how to implement data access layer. I want to use EntityFramework Code First approach. I was thinking about Repository pattern, but is this really necessary? I have read that it is only the next layer on top of ORM, which isn't really needed. So instead of writing method like:

GetAllPosts(Tag t) {
    db.Posts.Where(p => p.Tags.Contains(t)).Skip(x).Take(y).Select(p => p);
}

I create db context in controller and write the same query? I don't need to implement paging and write wrappers around my models.

1
  • Refer to the DRY principle: Don't Repeat Yourself. In the short term it may take longer to setup (not that longer compared to much copy and pasting), but in the long term it will save you much time for maintenance and testing hence debugging - which we all know can take a lot longer than writing the code in the first place. Commented Jun 25, 2013 at 8:03

2 Answers 2

2

What you may have heard about the Repository pattern is that it's falling out of favour in some camps - see for instance Jimmy Bogard's blog. This doesn't mean that queries should be written directly in controllers, unless your application is very, very simple.

As has been noted, your queries should be written in only one place which your controller can then use - this would either be in a Repository method or in a dedicated Query Object, both of which provide better abstraction and avoid duplication.

Regarding simplicitly - is your application intended to have multiple front-ends which will require a separate assembly for your data access layer? If not you might want to consider merging the two assemblies and just using namespaces to keep things organised.

Sign up to request clarification or add additional context in comments.

Comments

1

Not sure whether this question belongs here.

Anyway, if you write data access logic in your controller, and the same logic is required in another controller, what would you do? Copy-Paste this into new controller? That's just not good. Anytime, you are copying and pasting you need to step back, there must be something wrong here (aka code smell).

Separating the logic into different layer will make your code more maintainable and testable. Trust me!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.