Search code examples
asp.net-mvcentity-frameworkormrepository-patternpoco

Some issues about Rob Conery's repository pattern


Please read my update at the end of question after reading the answers:

I'm trying to apply repository pattern as Rob Conery's described on his blog under "MVC Storefront". But I want to ask about some issues that I had before I apply this design pattern.

Rob made his own "Model" and used some ORM "LINQ to SQL or Entity Framework (EF)" to map his database to Entities.

Then he used custom Repositories which gives IQueryable<myModel> and in these repositories he made sort of Mapping or "Parsing" between ORM Entities and his Model classes.

What I'm asking here:

Is it possible to make custom mapping between ORM Entities and my model "classes" and load just properties that I want? I hope the point is clear.

Update For POCO

**

This is what I decided after many of suggestions and many of tries:

**

After all and with respect to Mr. Rob Conery's opinion I've got better solution as:

  1. I built my model as "POCOs" and put them in my "Models Layers" so they had nothing to do with the "edmx" file.
  2. Built my repositories to deal with this "POCO" model dependent on "DbContext"
  3. Then I created a "ViewModels" to get just the information that needed by view from those repositories.

So I do not need to add one more layer to be between "EF Models" and "My Model". I just twist my model a little and force EF to deal with it.

As I see this pattern is better than Rob Conery's one.


Solution

  • Yes, it's possible if you're using LINQ to SQL. All you need to do is use projection to pull out the data you want into an object of your choosing. You don't need all this decoration with interfaces and whatnot - if you use a model specific to a view (which it sounds like you need) - create a ViewModel class.

    Let's call it ProductSummaryView:

    public class ProductSummaryView{
       public string Name {get;set;}
       public decimal Price {get;set;}
    }
    

    Now load it from the repository:

    var products= from p in _repository.GetAllProducts
                  where p.Price > 100
                  select new ProductSummaryView {
                      Name=p.ProductName,
                      Price=p.Price
    
                  }
    

    This will pull all products where the price > 100 and return an IQueryable. In addition, since you're only asking for two columns, only two columns will be specified in the SQL call.