Nhibernate, нужна помощь, чтобы исправить мой запрос выбора - PullRequest
0 голосов
/ 23 декабря 2011

Я новичок в nhibernate.я использую nhibernate 3. вот что мне нужно сделать, выбрать пользователя с его идентификатором 1. если этого пользователя не существует, вернуть значение null.

var selectedUser = session.Query ().Где (u => u.Id == 1) .FirstOrDefault ();

                if (selectedUser == null)
                {
                    userID = (int)session.Save(user);
                }

мой запрос на выборку не выполняется.

вот сообщение об ошибке, которое я получил.

could not execute query\r\n[ select TOP (@p0) user0_.Id as Id0_, user0_.Username as Username0_, user0_.Password as Password0_, user0_.CreateDate as CreateDate0_, user0_.Avatar as Avatar0_, user0_.AccountTypeId as AccountT6_0_, user0_.FirstName as FirstName0_, user0_.LastName as LastName0_, user0_.MiddleName as MiddleName0_, user0_.Email as Email0_, user0_.OtherId as OtherId0_ from [User] user0_ where user0_.Id=@p1 ]\r\n  Name:p1 - Value:1\r\n[SQL: select TOP (@p0) user0_.Id as Id0_, user0_.Username as Username0_, user0_.Password as Password0_, user0_.CreateDate as CreateDate0_, user0_.Avatar as Avatar0_, user0_.AccountTypeId as AccountT6_0_, user0_.FirstName as FirstName0_, user0_.LastName as LastName0_, user0_.MiddleName as MiddleName0_, user0_.Email as Email0_, user0_.OtherId as OtherId0_ from [User] user0_ where user0_.Id=@p1]"}
 [NHibernate.Exceptions.GenericADOException]: {"could not execute query\r\n[ select TOP (@p0) user0_.Id as Id0_, user0_.Username as Username0_, user0_.Password as Password0_, user0_.CreateDate as CreateDate0_, user0_.Avatar as Avatar0_, user0_.AccountTypeId as AccountT6_0_, user0_.FirstName as FirstName0_, user0_.LastName as LastName0_, user0_.MiddleName as MiddleName0_, user0_.Email as Email0_, user0_.OtherId as OtherId0_ from [User] user0_ where user0_.Id=@p1 ]\r\n  Name:p1 - Value:1\r\n[SQL: select TOP (@p0) user0_.Id as Id0_, user0_.Username as Username0_, user0_.Password as Password0_, user0_.CreateDate as CreateDate0_, user0_.Avatar as Avatar0_, user0_.AccountTypeId as AccountT6_0_, user0_.FirstName as FirstName0_, user0_.LastName as LastName0_, user0_.MiddleName as MiddleName0_, user0_.Email as Email0_, user0_.OtherId as OtherId0_ from [User] user0_ where user0_.Id=@p1]"}
Data: {System.Collections.ListDictionaryInternal}
HelpLink: null
InnerException: {"Invalid object name 'User'."}
Message: "could not execute query\r\n[ select TOP (@p0) user0_.Id as Id0_, user0_.Username as Username0_, user0_.Password as Password0_, user0_.CreateDate as CreateDate0_, user0_.Avatar as Avatar0_, user0_.AccountTypeId as AccountT6_0_, user0_.FirstName as FirstName0_, user0_.LastName as LastName0_, user0_.MiddleName as MiddleName0_, user0_.Email as Email0_, user0_.OtherId as OtherId0_ from [User] user0_ where user0_.Id=@p1 ]\r\n  Name:p1 - Value:1\r\n[SQL: select TOP (@p0) user0_.Id as Id0_, user0_.Username as Username0_, user0_.Password as Password0_, user0_.CreateDate as CreateDate0_, user0_.Avatar as Avatar0_, user0_.AccountTypeId as AccountT6_0_, user0_.FirstName as FirstName0_, user0_.LastName as LastName0_, user0_.MiddleName as MiddleName0_, user0_.Email as Email0_, user0_.OtherId as OtherId0_ from [User] user0_ where user0_.Id=@p1]"
Source: "NHibernate"
StackTrace: "   at NHibernate.Loader.Loader.DoList(ISessionImplementor session,    QueryParameters queryParameters)\r\n   at NHibernate.Loader.Loader.ListIgnoreQueryCache(ISessionImplementor session, QueryParameters queryParameters)\r\n   at NHibernate.Loader.Loader.List(ISessionImplementor session, QueryParameters queryParameters, ISet`1 querySpaces, IType[] resultTypes)\r\n   at NHibernate.Hql.Ast.ANTLR.Loader.QueryLoader.List(ISessionImplementor session, QueryParameters queryParameters)\r\n   at NHibernate.Hql.Ast.ANTLR.QueryTranslatorImpl.List(ISessionImplementor session, QueryParameters queryParameters)\r\n   at NHibernate.Engine.Query.HQLQueryPlan.PerformList(QueryParameters queryParameters, ISessionImplementor session, IList results)\r\n   at NHibernate.Impl.SessionImpl.List(IQueryExpression queryExpression, QueryParameters queryParameters, IList results)\r\n   at NHibernate.Impl.AbstractSessionImpl.List(IQueryExpression queryExpression, QueryParameters parameters)\r\n   at NHibernate.Impl.ExpressionQu

eryImpl.List () \ r \ n в NHibernate.\ n в NHibernate.Linq.NhQueryProvider.Execute [TResult] (выражение выражения) \ r \ n в System.Linq.Queryable.FirstOrDefault [TSource] (источник IQueryable`1) \ r \ n в DevelopmentStack.Domain.Repositories.Concrete.NUserRepository.AddUser (Пользователь-пользователь) в C: \ code \ net \ DevelopmentStack \ DevelopmentStack.Domain \ Repositories \ Concrete \ NUserRepository.cs: строка 30 "TargetSite: {System.Collections.IList DoList (NHibernate.Engine.ISessionImplementor, NHibernate).Engine.QueryParameters)}>

Ответы [ 2 ]

1 голос
/ 23 декабря 2011

Вероятно, это связано с тем, что пользователь является зарезервированным ключевым словом.Если вы отобразили его в hbm, убедитесь, что вы указали экранирование в названии таблицы: `Пользователь (пользователь должен быть окружен` `Я не могу писать правильно из-за уценки) или [Пользователь] .Разница между ними заключается в том, что второй не заботится о диалекте.

0 голосов
/ 23 декабря 2011

Try:

var selectedUser = session.Get<User>(1);

Вы всегда должны использовать Get вместо запроса при получении сущности по ее ID.Если объект не существует, то будет возвращено значение NULL.

...