I get an error in my first (current) request nhibernate Initializing [type] -failed ... session or session closed

I just started with NHibernate, created my mappings using white NHibernate, as follows:

public class CustomerMap : ClassMap<Customer>
{
    public CustomerMap()
    {
        Id(x => x._id, "Id");
        Map(x => x._KdNr, "KdNr");
        Map(x => x._Name, "Name");
        HasMany(x => x._Contact)
            .Table("Contacts")
            .KeyColumn("FKCustomerID")
            .LazyLoad();
    }
}


public class ContactMap : ClassMap<Contact>
{
    public ContactMap()
    {
        Id(x => x._id, "Id");
        Map(x => x._Name, "Name");
    }
}

And to save new entries also works:

    public static void AddCustomer(Customer cust)
    {
        using (var session = SessionFactory.Instance.OpenSession())
        {
            session.Save(cust);
            session.Save(cust._Contact);
            session.Flush();
        }
    }

Then I tried to select the client that I added using:

        using (var session = SessionFactory.Instance.OpenSession())
        {
            try
            {
                var v = session.CreateQuery("from Customer").List<Customers>();
                return (List<Customer>)v;
            }
            catch
            {
                session.Close();
                throw;
            }
            finally
            {
                session.Disconnect();
            }
        }
    }

The client is also loaded in order, but the contacts inside do not link with the following error:

Initialization [fnh.DataModel.Customer # d2f2d1c5-7d9e-4f77-8b4f-9e200088187b] -failed lazily initialize the role collection: fnh.DataModel.Kunde._Contact, session or session is not closed

But I can’t understand where the error comes from, because the session closes after the execution of my HQL error ...

+3
1

, , .. . , , viewmodel? , .

  • ( Open Session In View). , NH- ?

  • .Naz.Lazyload() . ( )

  • , . automapper, .

:

- , . , , . - , ..

Open Session , , -, - NH . ( , "" ). , (, .close() "" ). - :

  • global.asax - Application_BeginRequest Application_EndRequest (. ) , .

  • http ( , , ) (. )

    /li >

, , : " !" - , , ? factory.

  • , ( , , , NH-). OnActionExecuted, , . OnResultExecuted, .

, Open Session in View, , - , .

3 2, , , . , ViewModel , ViewModel Id - , , 3 - -, (- ).

+2

Source: https://habr.com/ru/post/1772331/


All Articles