简体   繁体   中英

Linq to NHibernate repository implementation details

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?

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.

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();

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, ie repository.Single(lambda) , etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM