开发者

Another repository-pattern question: how to deal with domain model projections?

I've read a lot about repository pattern implementation and I st开发者_如何学运维ill can't find out how should I implement entity projections querying?

For example I have large and complex product entity, but I want to display only product's name and it's id. Where should i implement this projection? In my entity repository or in a caller code?


I do this in the repository.

For instance, my ProductRepository interface would look like this:

interface IProductRepository
{
    Product Get( int productId );

    void Save( Product product );

    ProductView FindProducts(string productNameSearch);
}

Where ProductView is a simplified representation of Product. (Only containing name and id for instance).

The projection to get a ProductView, is something that has to be abstracted away, and the repository is a good place for it, imho.


I've been dreaming up the following pattern recently:

interface IRepository 
{
    Product FindByName(string name);
    ProjectionType FindByName<ProjectionType>(string name, 
        Expression<Func<Product, ProjectionType>> selector);
    // ...
}

With this pattern, you can for instance specify projections on the fly with LINQ expressions and anonymous classes, like this:

var productView = repository.FindByName("foo", 
    p => new { p.SomeProperty, p.SomeOtherProperty } );

Which I think is pretty neat. With NHibernate.Linq, an implementation might look like this:

ProjectionType FindByName<ProjectionType>(string name, Expression<Func<Product, ProjectionType>> selector) 
{
    using(var session = this.sessionFactory.OpenSession()) {
        return session.Linq<Product>()
                      .Where(p => p.Name.Equals(name))
                      .Select(selector)
                      .SingleOrDefault();
    }
}

DISCLAIMER: Beware of bugs or bad style in above code. Might not even compile. This is just from the tip of my head. But I think the idea should be pretty clear.

Any thoughts?


Have a look here and you'll understand why it is difficult.

http://ayende.com/blog/4784/architecting-in-the-pit-of-doom-the-evils-of-the-repository-abstraction-layer

http://lostechies.com/jimmybogard/2009/09/11/wither-the-repository/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜