guyl
guyl

Reputation: 2242

How to perform database queries using nhibernate and multiple repositories (under window service)

I know that this question asked a lot (i think) but i could not find a clear answer in the most smart programmer out there (google). I have implemented some repositories (not a generic one ) but per entity one.

public class Person
{
    public string Name { get; set; }
    public int Id { get; set; }
}

public class Product
{
    public int ProductId { get; set; }
}

public class PersonRepository
{
    ISession Session { get; set; }

    public Person GetById(int id) 
    {
        //...  
    }

    public IEnumerable<Person> GetAll()
    { 
        //... 
    }

}

public class ProductRepository
{
    ISession Session { get; set; }


    public Product GetById(int id)
    {
        //...  
    }

    public IEnumerable<Product> GetAll()
    {
        //... 
    }
}

public class PostOfficeService
{
    ProductRepository _rep1 = new ProductRepository();
    PersonRepository _rep2 = new PersonRepository();

    public IEnumerable<Person> GetAllPersonWithSameIdAsProduct()
    {
        _rep1.GetAll().Where( ... )
        // ??? i want it to perform the query in the DB and not two queries in app memory
    }
}

Should i use the unit of work pattern ? there are a lot of data and info out there but can't put my finger on the "right" solution or is it a good solution at all ?

Upvotes: 1

Views: 387

Answers (1)

Tim Rogers
Tim Rogers

Reputation: 21713

The Unit-Of-Work pattern is to do with transactions - I can't see how it relates to this problem.

GetAllPersonWithSameIdAsProduct should be a method of one of your PersonRepository - or a third, more advanced, repository - since, above the repository level, you don't have access to the session. Another approach is to make your repositories accept ICriteria parameters and use a criteria-builder class to create your complex queries.

However using LINQ-To-NHibernate would make solving these problems easier as the IQueryable implementation becomes your repository, and your Service classes can query using LINQ without any knowledge that they are talking to a database.

Upvotes: 1

Related Questions