Nhibernate 'save' & # 8594; 'get' problem

Hello,

I use nhibernate and have problems registering a user on my site.

When a user wants to register, I create a new user account in the database and, strangely enough, after that the system registers the user.

Well, here’s the problem ... When I create a user account, I use

NHibernateSession.Save (legal entity); // does not save the user object immediately to the database. It is stored in the session.

And when I want to log in, I load the user by his username, and then get the null user object.

Why am I getting a null object and how can I make it work?

thanks

+3
source share
2 answers

Ok, I just experienced this:

        ISession session = s.CreateSession();

        User user = new User();

        user.Number = 122;
        user.UserName = "u";
        user.Id = 1;

        session.Save(user);
        User user1 = session.CreateCriteria<User>().Add(Restrictions.Eq("UserName", "u")).UniqueResult<User>();

        session.Flush();

First you select from CreateCriteria, and then to reset the insert. Therefore, so that he does not find anything.

I also tested with Get<User>(1)and returns the object passed to the Save method - the request is not executed.

However - why query the database since you have an entity?

In addition, you say that you use Get, and then say that you want to load UserName - is UserName the main key? Try loading the primary key.

+3
source

If your Save and Get are executed from different sessions, then Get will return null, because the object exists only in the internal cache of other sessions until it is discarded.

, L2 ( , L2 Save Flush).

+1

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


All Articles