Linq to Sql, Repositories, and Asp.Net MVC ViewData: How to remove redundancy?
Linq to SQL creates objects which are IQueryable and full of relations.
Html Helpers require specific interface objects likeIEnumerabl开发者_如何学Ce<SelectListItem>
.
What I think could happen:
- Reuse the objects from Linq to SQL without all the baggage, i.e., return Pocos from the Linq to SQL objects without additional Domain Model classes?
- Extract objects that easily convert to (or are) Html helper objects like the SelectListItem enumeration?
Is there any way to do this without breaking separation of concerns? Some neat oop trick to bridge the needs?
For example, if this were within a repository, the SelectListItem wouldn't be there. The select new
is a nice way to cut out an object from the Linq to SQL without the baggage but it's still referencing a class that shouldn't be referenced:
IEnumerable<SelectListItem> result = (from record in db.table
select new SelectListItem {
Selected = record.selected,
Text= record.Text,
Value= record.Value }
).AsEnumerable();
I have seen the user of an IService interface and Service class. Basically it's the step between the repository and the controller.
Pros:
- Allows for methods that manipulate the return values of IRepository actions
- Good separation of concerns
- Can be the bridge where the validation logic lives before the repository is involved.
- Can work with Dependency injection frameworks/patterns
Cons:
- Mucho duplication of code. Unless you expose the repository, you will probably be duplicating almost all of your IRepository methods in the IService
- Can become a "catch-all" class. The god class that does everything! Muahahaha... etc
I'm sure there are more, but that's something I've seen and used.
In this specific example, you can create a ToSelectListItem() method or similar in your partial class definition to remove duplication. Or maybe an extension method would be better to avoid some coupling there.
Edit: I generally use JSON web services with DTOs. I might have ProductDto that is my flattened JSON-friendly representation of my Product L2SQL entity. Then I just have to call select ProductDto.FromProduct(product) in my query. The duplication is now minimal.
精彩评论