views:

98

answers:

3

I'd like to have the following API for my MyTypeRepository:

var myChosenInstance = _myRepository.FindOne(x => x.MyProperty == "MyValue");

..and for the lambda to use used to construct a linq query within the repository, which is then used by Linq to NHibernate.

Is this possible? What would my repository FindOne method look like?

A: 

Something like this?

var f = new Func<MyType, bool>(x => x.MyProperty == "MyValue");
var query = from t in session.Linq<MyType>() 
            where f.Invoke(t) 
            select new { Id = c.Id, Name = c.Name };
//or...
var query = from c in collection 
            .Where(f) 
            select new { Id = c.Id, Name = c.Name };
var results = query.Single();
Ben Aston
+6  A: 
public EntityType FindOne<EntityType>(Expression<Func<EntityType,bool>> predicate)
{
    return session.Linq<EntityType>().FirstOrDefault(predicate);
}

I'm assuming

  1. that your repository class has an ISession variable called session
  2. that Linq-To-NHibernate has a working implementation of the FirstOrDefault() method (because I haven't tested it to confirm)

If your repository class has a type parameter Repository<EntityType>, then you can omit the type parameter from the method.

Jay
Jay - thanks...
Ben Aston
A: 

AS an alternative, here is a repository interface and implementation that exposes generic IQueryable, ICollection and IDictionary interfaces.

When using that, you just use LINQ extension methods for querying, i.e. repository.Single(lambda), etc.

Diego Mijelshon