Expose a repository as an IQueryable

醉酒当歌 提交于 2019-12-31 03:37:08

问题


I'd like to expose a Repository as an 'IQueryable' type.

The repository uses Linq to NHibernate to communicate with the database.

Can anyone point me at an example implementation?

For example, what would the corresponding 'GetEnumerator()' implementation on my repository look like?

Edit:

Would something like this be appropriate?

public class MyTypeRepository : IEnumerable<MyType>
{        
    IEnumerator<MyType> IEnumerable<MyType>.GetEnumerator()
    {
        return Session.Linq<MyType>().GetEnumerator();
    }


    IEnumerator IEnumerable.GetEnumerator()
    {
        return ((IEnumerable<MyType>)this).GetEnumerator();
    }

}

回答1:


This is a bad design.

An IQueryable is a question (lookup "query" in a dictionary). It's how you ask for data. It's what you should be giving to the Repository.

A Repository should be returning answers -- the data itself.

If the Repository is returning a IQueryable, you've pretty much negated the need for the Repository.




回答2:


I think a Repository can give you 1 or more IQueryables/IEnumerables, but not : a Repository is an IQueryable.

It could look like:

 public interface IPersonRepository
 {
    IEnumerable<Person> GetAllPersons();
    void AddPerson(Person person);

    // more...
 }

You could return IQeryable<Person> from GetAllPerson() but that may not be an improvement. IEnumerable is simpler, less coupling.




回答3:


Lots of opinions of this one, but Ayende (Oren Eini) seems to think IQueryable is ok to return and articulates his point rather well.




回答4:


Just return session.Linq<T>()



来源:https://stackoverflow.com/questions/3246702/expose-a-repository-as-an-iqueryable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!