开发者

How to iterate on an entire table using NHibernate?

I am looking for a simple NHibernate example which will show me how iterate on an entire table. Here is what I have so far, but it is not working. I am getting an "System.InvalidOperationException: Operation is not valid due to 开发者_StackOverflow社区the current state of the object.". What am I doing wrong?

    public IEnumerable<EMPDATA> getEMPData()
    {
        using (ISession session = NHibernateHelper.OpenSession())
        {
            IEnumerable<EMPDATA> empData = session.CreateQuery("from EMPDATA").Enumerable<EMPDATA>();
            return empData;
        }
    }

    public static void Main(System.String[] args)
    {
        log.Debug("Entered main");
        Console.WriteLine("Entered main");
        try
        {
            IEMPDataRepository repository = new EMPDataRepository();
            IEnumerable<EMPDATA> iterList = repository.getEMPData();
            while( iterList.GetEnumerator().MoveNext())
            {
                EMPDATA emp = iterList.GetEnumerator().Current;
                log.Debug(emp.EMP_ID);
            }
        }
        catch (System.Exception ex)
        {
            log.Error("Exception occured reading emp data", ex);
        }

Here is my mapping:


You request an Enumerable result, which probably relies on the session still beeing open.

since you Dispose the session after returning the Enumerable instance, you have closed the connection to the database.

EDIT: see NotSupportedException on IQuery's Enumerable when using statelesssession


Short answer: use .List instead of .Enumerable.


Longer answer:
1. I agree with Phill- looks like a job for a SP
2. Diego is (obviously) right, but if I were you i'd use SetFirstResult() and SetMaxResult() in order to control the amount of data you load into memory in each iteration (don't forget to sort by something when using this method, of course).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜