I need IQueryable inside my business logic assembly based on Domain entities. I want to use auto-mapper for this purposes due to big amount of similar entities.
Works:
_repository.GetList<AgentDto>()
.Select(dto => new Agent{Login = dto.Login, Password = dto.Password})
.Where(...).ToList();
Does not work (I could not place Where (another assembly) before Select):
_repository.GetList<AgentDto>()
.Select(dto => ToAgent(dto))
.Where(...).ToList();
private Agent ToAgent(AgentDto dto)
{
return new Agent{Login = dto.Login, Password = dto.Password};
}
Exception:
System.NotSupportedException was caught
Message=CustomerInfo.Domain.Support.Agent ToAgent(CustomerInfo.DAL.DTO.AgentDto)
Source=NHibernate
StackTrace:
at NHibernate.Linq.Visitors.HqlGeneratorExpressionTreeVisitor.VisitMethodCallExpression(MethodCallExpression expression)
at NHibernate.Linq.Visitors.HqlGeneratorExpressionTreeVisitor.VisitExpression(Expression expression)
at NHibernate.Linq.Visitors.HqlGeneratorExpressionTreeVisitor.VisitMemberExpression(MemberExpression expression)
at NHibernate.Linq.Visitors.HqlGeneratorExpressionTreeVisitor.VisitExpression(Expression expression)
at NHibernate.Linq.Visitors.HqlGeneratorExpressionTreeVisitor.VisitBinaryExpression(BinaryExpression expression)
at NHibernate.Linq.Visitors.HqlGeneratorExpressionTreeVisitor.VisitExpression(Expression expression)
at NHibernate.Linq.Visitors.HqlGeneratorExpressionTreeVisitor.VisitBinaryExpression(BinaryExpression expression)
at NHibernate.Linq.Visitors.HqlGeneratorExpressionTreeVisitor.VisitExpression(Expression expression)
at NHibernate.Linq.Visitors.HqlGeneratorExpressionTreeVisitor.Visit(Expression expression, VisitorParameters parameters)
at NHibernate.Linq.Visitors.QueryModelVisitor.VisitWhereClause(WhereClause whereClause, QueryModel queryModel, Int32 index)
at Remotion.Linq.Clauses.WhereClause.Accept(IQueryModelVisitor visitor, QueryModel queryModel, Int32 index)
at Remotion.Linq.QueryModelVisitorBase.VisitBodyClauses(ObservableCollection`1 bodyClauses, QueryModel queryModel)
at Remotion.Linq.QueryModelVisitorBase.VisitQueryModel(QueryModel queryModel)
at NHibernate.Linq.Visitors.QueryModelVisitor.Visit()
at NHibernate.Linq.Visitors.QueryModelVisitor.GenerateHqlQuery(QueryModel queryModel, VisitorParameters parameters, Boolean root)
at NHibernate.Linq.NhLinqExpression.Translate(ISessionFactoryImplementor sessionFactory)
at NHibernate.Hql.Ast.ANTLR.ASTQueryTranslatorFactory.CreateQueryTranslators(String queryIdentifier, IQueryExpression queryExpression, String collectionRole, Boolean shallow, IDictionary`2 filters, ISessionFactoryImplementor factory)
at NHibernate.Engine.Query.HQLExpressionQueryPlan.CreateTranslators(String expressionStr, IQueryExpression queryExpression, String collectionRole, Boolean shallow, IDictionary`2 enabledFilters, ISessionFactoryImplementor factory)
at NHibernate.Engine.Query.HQLExpressionQueryPlan..ctor(String expressionStr, IQueryExpression queryExpression, String collectionRole, Boolean shallow, IDictionary`2 enabledFilters, ISessionFactoryImplementor factory)
at NHibernate.Engine.Query.HQLExpressionQueryPlan..ctor(String expressionStr, IQueryExpression queryExpression, Boolean shallow, IDictionary`2 enabledFilters, ISessionFactoryImplementor factory)
at NHibernate.Engine.Query.QueryPlanCache.GetHQLQueryPlan(IQueryExpression queryExpression, Boolean shallow, IDictionary`2 enabledFilters)
at NHibernate.Impl.AbstractSessionImpl.GetHQLQueryPlan(IQueryExpression queryExpression, Boolean shallow)
at NHibernate.Impl.AbstractSessionImpl.CreateQuery(IQueryExpression queryExpression)
at NHibernate.Linq.DefaultQueryProvider.PrepareQuery(Expression expression, IQuery& query, NhLinqExpression& nhQuery)
at NHibernate.Linq.DefaultQueryProvider.Execute(Expression expression)
at NHibernate.Linq.DefaultQueryProvider.Execute[TResult](Expression expression)
at System.Linq.Queryable.Count[TSource](IQueryable`1 source, Expression`1 predicate)
at CustomerInfo.BLL.Authentication.AgentManagementService.ValidateAgent(String agentLogin, String password) in D:\Projects\CustomerInfo\CustomerInfo.BLL\Authentication\AgentManagementService.cs:line 49
InnerException:
You need to think about how NHibernate Linq provider works. It cannot process everything you throw at it. NHibernate's Linq provider transforms lambda expressions to HQL and eventually to SQL. There is only a limited subset of expressions that it can support. Anything you enter as an expression must be convertible to SQL and execute in the database engine itself.
NHibernate Linq provider is extensible. If you need to use some expressions that aren't supported by NH Linq provider, and you think that they can be represented in SQL, you can write your own extension.
However, your case is pretty simple. You don't need to extend NHibernate to do it. NHibernate Linq provider doesn't support your expression, but Linq to objects does. Just reverse the order in your query, and it should work as expected:
_repository.GetList<AgentDto>()
.Where(...).ToList()
.Select(dto => ToAgent(dto)).ToList();
.ToList() after .Where() will execute NHibernate query and return a list of AgentDto objects. .Select method after that is in fact executing as Linq to objects - on a list of AgentDto objects in memory.
I think if you simply put the Where before the Select you'll be fine.
Related
Using Orchard.Projections module, it's not possible to search in Unicode text. For example the result query is Select ... From ... Where ... Col Like '%term%' but we expected Select ... From ... Where ... Col Like N'%term%' (N included after Like). Looking it up in code we find public static BinaryExpression Like() in Orchard.ContentManagement.HqlRestrictions. By adding N and changing value = "'%" + FormatValue(value, false) + "%'"; into value = "N'%" + FormatValue(value, false) + "%'"; we get this error:
NHibernate.Hql.Ast.ANTLR.QuerySyntaxException was caught
HResult=-2146232832
Message=Exception of type 'Antlr.Runtime.MismatchedTokenException' was thrown. near line 9, column 61
Source=NHibernate
StackTrace:
at NHibernate.Hql.Ast.ANTLR.ErrorCounter.ThrowQueryException() in c:\Users\sebros\Documents\My Projects\nhibernate-core\src\NHibernate\Hql\Ast\ANTLR\ErrorCounter.cs:line 73
at NHibernate.Hql.Ast.ANTLR.HqlParseEngine.Parse() in c:\Users\sebros\Documents\My Projects\nhibernate-core\src\NHibernate\Hql\Ast\ANTLR\QueryTranslatorImpl.cs:line 479
at NHibernate.Hql.Ast.ANTLR.ASTQueryTranslatorFactory.CreateQueryTranslators(String queryString, String collectionRole, Boolean shallow, IDictionary`2 filters, ISessionFactoryImplementor factory) in c:\Users\sebros\Documents\My Projects\nhibernate-core\src\NHibernate\Hql\Ast\ANTLR\ASTQueryTranslatorFactory.cs:line 19
at NHibernate.Engine.Query.HQLStringQueryPlan.CreateTranslators(String hql, String collectionRole, Boolean shallow, IDictionary`2 enabledFilters, ISessionFactoryImplementor factory) in c:\Users\sebros\Documents\My Projects\nhibernate-core\src\NHibernate\Engine\Query\HQLStringQueryPlan.cs:line 24
at NHibernate.Engine.Query.HQLStringQueryPlan..ctor(String hql, String collectionRole, Boolean shallow, IDictionary`2 enabledFilters, ISessionFactoryImplementor factory) in c:\Users\sebros\Documents\My Projects\nhibernate-core\src\NHibernate\Engine\Query\HQLStringQueryPlan.cs:line 16
at NHibernate.Engine.Query.HQLStringQueryPlan..ctor(String hql, Boolean shallow, IDictionary`2 enabledFilters, ISessionFactoryImplementor factory) in c:\Users\sebros\Documents\My Projects\nhibernate-core\src\NHibernate\Engine\Query\HQLStringQueryPlan.cs:line 14
at NHibernate.Engine.Query.QueryPlanCache.GetHQLQueryPlan(String queryString, Boolean shallow, IDictionary`2 enabledFilters) in c:\Users\sebros\Documents\My Projects\nhibernate-core\src\NHibernate\Engine\Query\QueryPlanCache.cs:line 62
at NHibernate.Impl.AbstractSessionImpl.GetHQLQueryPlan(String query, Boolean shallow) in c:\Users\sebros\Documents\My Projects\nhibernate-core\src\NHibernate\Impl\AbstractSessionImpl.cs:line 310
at NHibernate.Impl.AbstractSessionImpl.CreateQuery(String queryString) in c:\Users\sebros\Documents\My Projects\nhibernate-core\src\NHibernate\Impl\AbstractSessionImpl.cs:line 289
at Orchard.ContentManagement.DefaultHqlQuery.Slice(Int32 skip, Int32 count) in d:\Projects\...\src\Orchard\ContentManagement\DefaultHqlQuery.cs:line 188
at Orchard.Projections.Services.ProjectionManager.GetContentItems(Int32 queryId, Int32 skip, Int32 count)
at Orchard.Projections.Drivers.ProjectionPartDriver.<>c__DisplayClass2e.<Display>b__1e(Object shape)
at Orchard.ContentManagement.Drivers.ContentPartDriver`1.<>c__DisplayClass12.<ContentShape>b__11(BuildShapeContext ctx) in d:\Projects\...\src\Orchard\ContentManagement\Drivers\ContentPartDriver.cs:line 135
at Orchard.ContentManagement.Drivers.ContentPartDriver`1.<>c__DisplayClass15.<ContentShapeImplementation>b__14(BuildShapeContext ctx) in d:\Projects\...\src\Orchard\ContentManagement\Drivers\ContentPartDriver.cs:line 140
at Orchard.ContentManagement.Drivers.ContentShapeResult.ApplyImplementation(BuildShapeContext context, String displayType) in d:\Projects\...\src\Orchard\ContentManagement\Drivers\ContentShapeResult.cs:line 45
at Orchard.ContentManagement.Drivers.ContentShapeResult.Apply(BuildDisplayContext context) in d:\Projects\...\src\Orchard\ContentManagement\Drivers\ContentShapeResult.cs:line 21
at Orchard.ContentManagement.Drivers.CombinedResult.Apply(BuildDisplayContext context) in d:\Projects\...\src\Orchard\ContentManagement\Drivers\CombinedResult.cs:line 28
at Orchard.ContentManagement.Drivers.Coordinators.ContentPartDriverCoordinator.<>c__DisplayClassa.<BuildDisplay>b__9(IContentPartDriver driver) in d:\Projects\...\src\Orchard\ContentManagement\Drivers\Coordinators\ContentPartDriverCoordinator.cs:line 49
at Orchard.InvokeExtensions.Invoke[TEvents](IEnumerable`1 events, Action`1 dispatch, ILogger logger) in d:\Projects\...\src\Orchard\InvokeExtensions.cs:line 17
InnerException:
line 9, column 61 indicates the position of 'N'.
Any idea?
How can we use this module to search in unicode text without changing database collation?
Orchard version is 1.8.1
Quick fix. I've changed collation setting directly of database
I am trying some thing like
GetQueryable<Requirement>()
.OrderByDescending( y => y.BidsReceieved.Count() )
.ToList();
but its failing, with exception
Infrastructure.DataAccess.RequirementRepositoryTests.IsOrderbyBidCountWorking' failed: NHibernate.Hql.Ast.ANTLR.QuerySyntaxException : Exception of type 'Antlr.Runtime.NoViableAltException' was thrown. [.OrderByDescending[KHM.Domain.Entities.Requirement,System.Int32](NHibernate.Linq.NhQueryable`1[KHM.Domain.Entities.Requirement], Quote((y, ) => (.Count[KHM.Domain.Entities.Bid](y.BidsRecieved, ))), )]
at NHibernate.Hql.Ast.ANTLR.ErrorCounter.ThrowQueryException()
at NHibernate.Hql.Ast.ANTLR.HqlSqlTranslator.Translate()
at NHibernate.Hql.Ast.ANTLR.QueryTranslatorImpl.DoCompile(IDictionary`2 replacements, Boolean shallow, String collectionRole)
at NHibernate.Hql.Ast.ANTLR.ASTQueryTranslatorFactory.CreateQueryTranslators(IASTNode ast, String queryIdentifier, String collectionRole, Boolean shallow, IDictionary`2 filters, ISessionFactoryImplementor factory)
at NHibernate.Hql.Ast.ANTLR.ASTQueryTranslatorFactory.CreateQueryTranslators(String queryIdentifier, IQueryExpression queryExpression, String collectionRole, Boolean shallow, IDictionary`2 filters, ISessionFactoryImplementor factory)
at NHibernate.Engine.Query.QueryPlanCache.GetHQLQueryPlan(IQueryExpression queryExpression, Boolean shallow, IDictionary`2 enabledFilters)
at NHibernate.Impl.AbstractSessionImpl.GetHQLQueryPlan(IQueryExpression queryExpression, Boolean shallow)
at NHibernate.Impl.AbstractSessionImpl.CreateQuery(IQueryExpression queryExpression)
at NHibernate.Linq.NhQueryProvider.PrepareQuery(Expression expression, IQuery& query, NhLinqExpression& nhQuery)
at NHibernate.Linq.NhQueryProvider.Execute[TResult](Expression expression)
at Remotion.Data.Linq.QueryableBase`1.GetEnumerator() in :line 0
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
DataAccess\Repositories\RequirementsRepository.cs(49,0): at KHM.Infrastructure.DataAccess.Repositories.RequirementsRepository.Orderbybids()
Infrastructure\DataAccess\RequirementRepositoryTests.cs(115,0): at KHM.IntegrationTests.Infrastructure.DataAccess.RequirementRepositoryTests.IsOrderbyBidCountWorking()
I want to order the requirements based on the no of bids it received.
I'm using linq-to-nhibernate, I am using nhibernate3.1
is BidsReceieved a colleciton?
if so, I think you should use BidsReceieved.Count but not BidsReceieved.Count(). No bracket here.
Continuation to the previous question, I tried to avoid the problem another way:
Just for the reminder:
My database schema is described below:
Form <-> Log
<--->>Seller1
<--->>Seller2
<--->>Seller3
I have a major entity (Form), one to
one relationship to another object
(Log) And one to many relationship to
the childs (Sellers).
I want to pull out all the Forms that
one of their Sellers meets certain
conditions.
I tried like this now:
[Test]
public void Can_Get_Forms_Where_CorporationNumber_Is_510778087_Metohd1()
{
var CorporationNumber = "513514950";
var list1 = sellerRepository
.Where(x => x.CorporationNumber == CorporationNumber)
.Select(x => x.Form)
.Fetch(x => x.Log)
.Take(10).ToList();
CollectionAssert.IsNotEmpty(list1);
}
But unfortunately I get NullReferenceException:
TestUsingDevelopmentDataBase.Moch.BillOfSale.Data.FormRepositoryTests.Can_Get_Forms_Where_CorporationNumber_Is_510778087_Metohd1:
System.NullReferenceException : Object
reference not set to an instance of an
object
EDIT: stacktrace:
at
NHibernate.Linq.Visitors.ResultOperatorProcessors.ProcessFetch.Process(FetchRequestBase
resultOperator, QueryModelVisitor
queryModelVisitor, IntermediateHqlTree
tree) in
d:\CSharp\NH\nhibernate\src\NHibernate\Linq\Visitors\ResultOperatorProcessors\ProcessFetch.cs:line
11 at
NHibernate.Linq.Visitors.ResultOperatorProcessors.ProcessFetchOne.Process(FetchOneRequest
resultOperator, QueryModelVisitor
queryModelVisitor, IntermediateHqlTree
tree) in
d:\CSharp\NH\nhibernate\src\NHibernate\Linq\Visitors\ResultOperatorProcessors\ProcessFetchOne.cs:line
9 at
NHibernate.Linq.Visitors.ResultOperatorProcessors.ResultOperatorProcessor1.Process(ResultOperatorBase
resultOperator, QueryModelVisitor
queryModel, IntermediateHqlTree tree)
in
d:\CSharp\NH\nhibernate\src\NHibernate\Linq\Visitors\ResultOperatorProcessors\ResultOperatorProcessor.cs:line
17 at
NHibernate.Linq.Visitors.ResultOperatorProcessors.ResultOperatorMap.Process(ResultOperatorBase
resultOperator, QueryModelVisitor
queryModel, IntermediateHqlTree tree)
in
d:\CSharp\NH\nhibernate\src\NHibernate\Linq\Visitors\ResultOperatorProcessors\ResultOperatorMap.cs:line
24 at
NHibernate.Linq.Visitors.QueryModelVisitor.VisitResultOperator(ResultOperatorBase
resultOperator, QueryModel queryModel,
Int32 index) in
d:\CSharp\NH\nhibernate\src\NHibernate\Linq\Visitors\QueryModelVisitor.cs:line
125 at
Remotion.Data.Linq.Clauses.ResultOperatorBase.Accept(IQueryModelVisitor
visitor, QueryModel queryModel, Int32
index) at
Remotion.Data.Linq.QueryModelVisitorBase.VisitResultOperators(ObservableCollection1
resultOperators, QueryModel
queryModel) at
Remotion.Data.Linq.QueryModelVisitorBase.VisitQueryModel(QueryModel
queryModel) at
NHibernate.Linq.Visitors.QueryModelVisitor.Visit()
in
d:\CSharp\NH\nhibernate\src\NHibernate\Linq\Visitors\QueryModelVisitor.cs:line
96 at
NHibernate.Linq.Visitors.QueryModelVisitor.GenerateHqlQuery(QueryModel
queryModel, VisitorParameters
parameters, Boolean root) in
d:\CSharp\NH\nhibernate\src\NHibernate\Linq\Visitors\QueryModelVisitor.cs:line
49 at
NHibernate.Linq.NhLinqExpression.Translate(ISessionFactoryImplementor
sessionFactory) in
d:\CSharp\NH\nhibernate\src\NHibernate\Linq\NhLinqExpression.cs:line
67 at
NHibernate.Hql.Ast.ANTLR.ASTQueryTranslatorFactory.CreateQueryTranslators(String
queryIdentifier, IQueryExpression
queryExpression, String
collectionRole, Boolean shallow,
IDictionary2 filters,
ISessionFactoryImplementor factory) in
d:\CSharp\NH\nhibernate\src\NHibernate\Hql\Ast\ANTLR\ASTQueryTranslatorFactory.cs:line
27 at
NHibernate.Engine.Query.HQLExpressionQueryPlan.CreateTranslators(String
expressionStr, IQueryExpression
queryExpression, String
collectionRole, Boolean shallow,
IDictionary2 enabledFilters,
ISessionFactoryImplementor factory) in
d:\CSharp\NH\nhibernate\src\NHibernate\Engine\Query\HQLExpressionQueryPlan.cs:line
34 at
NHibernate.Engine.Query.HQLExpressionQueryPlan..ctor(String
expressionStr, IQueryExpression
queryExpression, String
collectionRole, Boolean shallow,
IDictionary2 enabledFilters,
ISessionFactoryImplementor factory) in
d:\CSharp\NH\nhibernate\src\NHibernate\Engine\Query\HQLExpressionQueryPlan.cs:line
23 at
NHibernate.Engine.Query.HQLExpressionQueryPlan..ctor(String
expressionStr, IQueryExpression
queryExpression, Boolean shallow,
IDictionary2 enabledFilters,
ISessionFactoryImplementor factory) in
d:\CSharp\NH\nhibernate\src\NHibernate\Engine\Query\HQLExpressionQueryPlan.cs:line
17 at
NHibernate.Engine.Query.QueryPlanCache.GetHQLQueryPlan(IQueryExpression
queryExpression, Boolean shallow,
IDictionary2 enabledFilters) in
d:\CSharp\NH\nhibernate\src\NHibernate\Engine\Query\QueryPlanCache.cs:line
88 at
NHibernate.Impl.AbstractSessionImpl.GetHQLQueryPlan(IQueryExpression
queryExpression, Boolean shallow) in
d:\CSharp\NH\nhibernate\src\NHibernate\Impl\AbstractSessionImpl.cs:line
302 at
NHibernate.Impl.AbstractSessionImpl.CreateQuery(IQueryExpression
queryExpression) in
d:\CSharp\NH\nhibernate\src\NHibernate\Impl\AbstractSessionImpl.cs:line
258 at
NHibernate.Linq.NhQueryProvider.PrepareQuery(Expression
expression, IQuery& query,
NhLinqExpression& nhQuery) in
d:\CSharp\NH\nhibernate\src\NHibernate\Linq\NhQueryProvider.cs:line
42 at
NHibernate.Linq.NhQueryProvider.Execute(Expression
expression) in
d:\CSharp\NH\nhibernate\src\NHibernate\Linq\NhQueryProvider.cs:line
25 at
NHibernate.Linq.NhQueryProvider.Execute[TResult](Expression
expression) in
d:\CSharp\NH\nhibernate\src\NHibernate\Linq\NhQueryProvider.cs:line
102 at
Remotion.Data.Linq.QueryableBase1.GetEnumerator()
at
System.Collections.Generic.List1..ctor(IEnumerable1
collection) at
System.Linq.Enumerable.ToList[TSource](IEnumerable`1
source) at
TestUsingDevelopmentDataBase.Moch.BillOfSale.Data.FormRepositoryTests.Can_Get_Forms_Where_CorporationNumber_Is_510778087_Metohd1()
in
D:\Dev\NCommon\Moch.BillOfSale\Moch.BillOfSale.NHibenate.Tests\FormRepositoryTests.cs:line
207
The problem could be circumvented in a less well, as follows:
[Test]
public void Can_Get_Forms_Where_CorporationNumber_Is_510778087_Metohd2()
{
var CorporationNumber = "513514950";
var list2 = sellerRepository
.Where(x => x.CorporationNumber == CorporationNumber)
.Fetch(x => x.Form).ThenFetch(x => x.Log)
.Take(10).ToList().Select(x => x.Form);
CollectionAssert.IsNotEmpty(list2);
}
But of course we all prefer the elegant way and want to understand what lies behind the problem
I think Nhibernate doesn't like you fetching after a select. I ran into a null reference exception just like you did.
See my question here about it.
In Linq-to-Nhibernate, is it possible to use .Fetch() after a .Select()?
You might be able to .Select(x => x.Form) after your fetching in your second example before you .ToList() it, too.
I'm using Nhibernate 3.2 and this is still an issue. There should be a proper 'you can't fetch after a select' exception or something to spare us some pain.
We have a very strange error that sometimes we get this error when we want to save something from our WCF service. The object that we are saving contains NO invalid datetimes, we all check them before we save. When we see this error the database hangs sometimes and the WCF is in a faulty state. When I restart the DB and the IIS web app where the WCF is hosted and try to save again. It works..
We are clueless so if any one has some advice, please share
Following is the error:
2010-03-05 10:21:34,311 [5] ERROR ProjectX.Business.TTExceptionLogger - Exception somewhere in ReceiveResultsForMobile(): {0}
Castle.Services.Transaction.CommitResourceException: Could not commit transaction, one (or more) of the resources failed ---> System.Data.SqlTypes.SqlTypeException: SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
at System.Data.SqlTypes.SqlDateTime.FromTimeSpan(TimeSpan value)
at System.Data.SqlTypes.SqlDateTime.FromDateTime(DateTime value)
at System.Data.SqlClient.MetaType.FromDateTime(DateTime dateTime, Byte cb)
at System.Data.SqlClient.TdsParser.WriteValue(Object value, MetaType type, Byte scale, Int32 actualLength, Int32 encodingByteSize, Int32 offset, TdsParserStateObject stateObj)
at System.Data.SqlClient.TdsParser.TdsExecuteRPC(_SqlRPC[] rpcArray, Int32 timeout, Boolean inSchema, SqlNotificationRequest notificationRequest, TdsParserStateObject stateObj, Boolean isCommandProc)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at NHibernate.AdoNet.AbstractBatcher.ExecuteNonQuery(IDbCommand cmd)
at NHibernate.AdoNet.NonBatchingBatcher.AddToBatch(IExpectation expectation)
at NHibernate.Persister.Entity.AbstractEntityPersister.Update(Object id, Object[] fields, Object[] oldFields, Object rowId, Boolean[] includeProperty, Int32 j, Object oldVersion, Object obj, SqlCommandInfo sql, ISessionImplementor session)
at NHibernate.Persister.Entity.AbstractEntityPersister.UpdateOrInsert(Object id, Object[] fields, Object[] oldFields, Object rowId, Boolean[] includeProperty, Int32 j, Object oldVersion, Object obj, SqlCommandInfo sql, ISessionImplementor session)
at NHibernate.Persister.Entity.AbstractEntityPersister.Update(Object id, Object[] fields, Int32[] dirtyFields, Boolean hasDirtyCollection, Object[] oldFields, Object oldVersion, Object obj, Object rowId, ISessionImplementor session)
at NHibernate.Action.EntityUpdateAction.Execute()
at NHibernate.Engine.ActionQueue.Execute(IExecutable executable)
at NHibernate.Engine.ActionQueue.ExecuteActions(IList list)
at NHibernate.Engine.ActionQueue.ExecuteActions()
at NHibernate.Event.Default.AbstractFlushingEventListener.PerformExecutions(IEventSource session)
at NHibernate.Event.Default.DefaultFlushEventListener.OnFlush(FlushEvent event)
at NHibernate.Impl.SessionImpl.Flush()
at NHibernate.Transaction.AdoTransaction.Commit()
at Rhino.Commons.NHibernateTransactionAdapter.Commit()
at Rhino.Commons.Facilities.RhinoTransactionResourceAdapter.Commit()
at Castle.Services.Transaction.AbstractTransaction.Commit()
--- End of inner exception stack trace ---
at Castle.Services.Transaction.AbstractTransaction.Commit()
at Castle.Services.Transaction.StandardTransaction.Commit()
at Castle.Facilities.AutomaticTransactionManagement.TransactionInterceptor.Intercept(IInvocation invocation)
at Castle.DynamicProxy.AbstractInvocation.Proceed()
at IReceiveServiceProxy61c28a82c9a24e96957e32292b924889.Save(Receive instance)
at WcfInterfaceService.MobileServices.SaveReceiveLines(IEnumerable1 receiveLines, String warehouseCode, String username, String deviceNumber, Boolean removeOldReceiveLines) in D:\Project Docs\Clients\ClientX 09.08\Projects\ProjectX\ProjectX.WcfInterfaceService\MobileServices.svc.cs:line 567
at WcfInterfaceService.MobileServices.ProcessReceiveResults(List1 receiveLines, String warehouseCode, String username, String deviceNumber) in D:\Project Docs\Clients\ClientX 09.08\Projects\ProjectX\ProjectX.WcfInterfaceService\MobileServices.svc.cs:line 770
at WcfInterfaceService.MobileServices.ProcessResultsFromMobile(String receiveResult, String warehouseCode, String username, String deviceNumber) in D:\Project Docs\Clients\ClientX 09.08\Projects\ProjectX\ProjectX.WcfInterfaceService\MobileServices.svc.cs:line 668
Are you running SQL Server 2008? I ran into this same error today when using SQL Server 2008. On the database I had set the column to "date" instead of "datetime" because I do not care about the time portion. But there isn't a "date" data type in .NET so you use datetime.
For me I was passing along null datetime values which defaults to something like 1/1/0001 12:00:00 AM. So I was getting the same error you are seeing because it included the time portion.
For me I had to make my datetime value nullable and I also had to use the MsSql2008Dialect in NHibernate which supports the date datatype. More info about NHibernate and SQL Server 2008 here.
I'd check to make sure your database data type is set correctly and that you are using the MsSql2008Dialect if you are using SQL Server 2008.
I have two questions before I can give you an answer:
What kind of database do you use?
What kind of date is causing the exception?
Guess: you are using a database that has a smaller datetime range or accuracy than you use in your code. In that case, the exception is not caused by NHibernate, but by a feature of the database. It's not a bug but a feature.
I am trying to solve an issue when using a Castle ActiveRecord TransactionScope which is rolled back.
After the rollback, I am unable to query the Dog table. The "Dog.FindFirst()" line fails with "Could not perform SlicedFindAll for Dog", because it cannot insert dogMissingName.
using (new SessionScope())
{
try
{
var trans = new TransactionScope(TransactionMode.New, OnDispose.Commit);
try
{
var dog = new Dog
{
Name = "Snowy"
};
dog.Save();
var dogMissingName = new Dog();
dogMissingName.Save();
}
catch (Exception)
{
trans.VoteRollBack();
throw;
}
finally
{
trans.Dispose();
}
}
catch (Exception ex)
{
var dogFromDatabase = Dog.FindFirst();
Console.WriteLine("A dog: " + dogFromDatabase.Name);
}
}
Stacktrace is as follows:
Castle.ActiveRecord.Framework.ActiveRecordException: Could not perform SlicedFindAll for Dog ---> NHibernate.Exceptions.GenericADOException: could not insert: [Mvno.Dal.Dog#219e86fa-1081-490a-92d1-9d480171fcfd][SQL: INSERT INTO Dog (Name, Id) VALUES (?, ?)] ---> System.Data.SqlClient.SqlException: Cannot insert the value NULL into column 'Name', table 'Dog'; column does not allow nulls. INSERT fails.
The statement has been terminated.
ved System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
ved System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
ved System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)
ved System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
ved System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
ved System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)
ved System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)
ved System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe)
ved System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
ved NHibernate.AdoNet.AbstractBatcher.ExecuteNonQuery(IDbCommand cmd)
ved NHibernate.AdoNet.NonBatchingBatcher.AddToBatch(IExpectation expectation)
ved NHibernate.Persister.Entity.AbstractEntityPersister.Insert(Object id, Object[] fields, Boolean[] notNull, Int32 j, SqlCommandInfo sql, Object obj, ISessionImplementor session)
--- End of inner exception stack trace ---
ved NHibernate.Persister.Entity.AbstractEntityPersister.Insert(Object id, Object[] fields, Boolean[] notNull, Int32 j, SqlCommandInfo sql, Object obj, ISessionImplementor session)
ved NHibernate.Persister.Entity.AbstractEntityPersister.Insert(Object id, Object[] fields, Object obj, ISessionImplementor session)
ved NHibernate.Action.EntityInsertAction.Execute()
ved NHibernate.Engine.ActionQueue.Execute(IExecutable executable)
ved NHibernate.Engine.ActionQueue.ExecuteActions(IList list)
ved NHibernate.Engine.ActionQueue.ExecuteActions()
ved NHibernate.Event.Default.AbstractFlushingEventListener.PerformExecutions(IEventSource session)
ved NHibernate.Event.Default.DefaultAutoFlushEventListener.OnAutoFlush(AutoFlushEvent event)
ved NHibernate.Impl.SessionImpl.AutoFlushIfRequired(ISet`1 querySpaces)
ved NHibernate.Impl.SessionImpl.List(CriteriaImpl criteria, IList results)
ved NHibernate.Impl.CriteriaImpl.List(IList results)
ved NHibernate.Impl.CriteriaImpl.List()
ved Castle.ActiveRecord.ActiveRecordBase.SlicedFindAll(Type targetType, Int32 firstResult, Int32 maxResults, Order[] orders, ICriterion[] criteria)
--- End of inner exception stack trace ---
ved Castle.ActiveRecord.ActiveRecordBase.SlicedFindAll(Type targetType, Int32 firstResult, Int32 maxResults, Order[] orders, ICriterion[] criteria)
ved Castle.ActiveRecord.ActiveRecordBase.FindFirst(Type targetType, Order[] orders, ICriterion[] criteria)
ved Castle.ActiveRecord.ActiveRecordBase.FindFirst(Type targetType, ICriterion[] criteria)
ved Castle.ActiveRecord.ActiveRecordBase`1.FindFirst(ICriterion[] criteria)
If you look at the stack trace, you'll realize that the invalid dogMissingName record is still hanging around in the session's batched insertion buffer, even after the first attempt to perform the insertion failed. Calling Dog.FindFirst() later in the same session re-triggers an internal Flush() (which attempts once again the failed insert.)
From section 9.6 of the documentation:
From time to time the ISession will
execute the SQL statements needed to
synchronize the ADO.NET connection's
state with the state of objects held
in memory. This process, flush, occurs
by default at the following points
from some invocations of Find() or Enumerable()
from NHibernate.ITransaction.Commit()
from ISession.Flush()
Additionally, from section 9.7.2 of the documentation:
If you rollback the transaction you should immediately close and discard the current session
to ensure that NHibernate's internal state is consistent.
Simply moving using (new SessionScope()) inside the outermost try/catch may be a viable workaround (the initial insertion will fail, raise an exception which will take you out of the SessionScope, likely triggering a second failure on the same insert, failure which you finally catch -- also see "data is not flushed on SessionScope.Flush()" in com.googlegroups.castle-project-users.).
Alternatively, if you don't want to close the session, you should be able to simply change the session default flush behaviour (see the FlushMode class) so that it never flushes unless Flush() is called explicitly (e.g. before committing.) Note that managing flushing in this way will get complex and error-prone very quickly, though.
The key is right on Vlad's answer:
If you rollback the transaction you
should immediately close and discard
the current session to ensure that
NHibernate's internal state is
consistent.
After you understand and apply that, your code should then look like this:
try
{
using (new SessionScope())
using (var trans = new TransactionScope(TransactionMode.New, OnDispose.Commit))
{
try
{
var dog = new Dog { Name = "Snowy" };
dog.Save();
var dogMissingName = new Dog();
dogMissingName.Save();
}
catch (Exception)
{
trans.VoteRollBack();
throw;
}
}
}
catch (Exception ex)
{
using (new SessionScope())
{
var dogFromDatabase = Dog.FindFirst();
Console.WriteLine("A dog: " + dogFromDatabase.Name);
}
}