LINQ to NHibernate - .GroupBy().Skip().Take() cause an exception - nhibernate

NHibernate version 3.3.1.4000
Query:
IQueryable<Activity> activities = _repository.GetList<Activity>();
IQueryable<ActivityStatistic> statistics = activities
.GroupBy(activity => activity.ActivityLicense.SerialNumber)
.Select(grouping => new ActivityStatistic
{
ActivityCount = grouping.Count(),
LicenseCode = grouping.Key
})
.OrderBy(stat => stat.LicenseCode);
List<ActivityStatistic> result = statistics
.Skip(request.StartIndex)
.Take(request.Count)
.ToList();
If I comment Skip/Take code, it works properly. How can I make it to work together without calling ToList() after OrderBy using LINQ to NHibernate?
Thanks in advance.
Update:
Exception:
The method or operation is not implemented.
at NHibernate.Linq.GroupBy.AggregatingGroupByRewriter.FlattenSubQuery(SubQueryExpression subQueryExpression, QueryModel queryModel)
at NHibernate.Linq.GroupBy.AggregatingGroupByRewriter.ReWrite(QueryModel queryModel)
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.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 Remotion.Linq.QueryableBase`1.GetEnumerator()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at MBP.AuthorizationService.Logic.LicenseService.GetActivityStatistic(CommonRequest request, Int32& recordsCount) in D:\Projects\MBP.Launcher\MBP.AuthorizationService.Logic\LicenseService.cs:line 201

Michael Petito answered to the question:
This is a known issue that I just ran into as well:
nhibernate.jira.com/browse/NH-2566 – Michael Petito Aug 22 at 19:56
Waiting for new releases...

Related

NHibernate create criteria, add Restrictions on related table with nullable foreign key

I work on a Api project in .NET core 2.2 with NHibernate (5.2.5)
Table A has nullable foreign key from table B
I need to create a criteria to filter Table A, using a nullable foreign key (which is not null) that points to Table B, where the Status in Table B is 3
This is something what I have tried:
var criteria = _session.CreateCriteria<AgencyAgreement>();criteria.Add(Restrictions.Eq("BookingCartItem.Status", (int)BookingCartStatus.Cancelled));
also with and operator
criteria.Add(Restrictions.And(Restrictions.IsNotNull("BookingCartItem"), Restrictions.Eq("BookingCartItem.Status", (int)BookingCartStatus.Cancelled)));
but this is what I get as Error
at NHibernate.Persister.Entity.AbstractPropertyMapping.GetColumns(String propertyName)\r\n at NHibernate.Persister.Entity.AbstractPropertyMapping.ToColumns(String alias, String propertyName)\r\n at NHibernate.Loader.Criteria.CriteriaQueryTranslator.GetColumnsUsingProjection(ICriteria subcriteria, String propertyName)\r\n at NHibernate.Criterion.CriterionUtil.GetColumnNamesUsingPropertyName(ICriteriaQuery criteriaQuery, ICriteria criteria, String propertyName, Object value, ICriterion critertion)\r\n at NHibernate.Criterion.SimpleExpression.ToSqlString(ICriteria criteria, ICriteriaQuery criteriaQuery)\r\n at NHibernate.Criterion.LogicalExpression.ToSqlString(ICriteria criteria, ICriteriaQuery criteriaQuery)\r\n at NHibernate.Loader.Criteria.CriteriaQueryTranslator.GetWhereCondition()\r\n at NHibernate.Loader.Criteria.CriteriaJoinWalker..ctor(IOuterJoinLoadable persister, CriteriaQueryTranslator translator, ISessionFactoryImplementor factory, ICriteria criteria, String rootEntityName, IDictionary2 enabledFilters)\r\n at NHibernate.Loader.Criteria.CriteriaLoader..ctor(IOuterJoinLoadable persister, ISessionFactoryImplementor factory, CriteriaImpl rootCriteria, String rootEntityName, IDictionary2 enabledFilters)\r\n at NHibernate.Impl.SessionImpl.ListAsync(CriteriaImpl criteria, IList results, CancellationToken cancellationToken)\r\n at NHibernate.Impl.CriteriaImpl.ListAsync(IList results, CancellationToken cancellationToken)\r\n at NHibernate.Impl.CriteriaImpl.ListAsync[T](CancellationToken cancellationToken)\r\n at HASELT.merakzy.Services.Features.Documents.QueryTravelAgreements.Handler.Handle(Request request, CancellationToken cancellationToken) in C:\Users\Asus\Desktop\merakzy-sourcecode\merakzy-master\src\HASELT.merakzy.Services\Features\AgencyDocuments\QueryTravelAgreements.cs:line 115\r\n at MediatR.Pipeline.RequestPostProcessorBehavior2.Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate1 next)\r\n at MediatR.Pipeline.RequestPreProcessorBehavior2.Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate1 next)\r\n at lambda_method(Closure , Object )\r\n at Microsoft.Extensions.Internal.ObjectMethodExecutorAwaitable.Awaiter.GetResult()\r\n at Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)\r\n at System.Threading.Tasks.ValueTask`1.get_Result()\r\n at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeActionMethodAsync()\r\n at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeNextActionFilterAsync()\r\n at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context)\r\n at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)\r\n at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync()\r\n at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextExceptionFilterAsync()
var criteria = _session.CreateCriteria<AgencyAgreement>();
criteria.CreateCriteria(nameof(AgencyAgreement.BookingCartItem))
.Add(Restrictions.Eq("Status", (int)BookingCartStatus.Cancelled));
or using linq if the properties are known at compile time
var query = _session.Query<AgencyAgreement>();
query = query.Where(a => a.BookingCartItem.Status == (int)BookingCartStatus.Cancelled);

Time-out error using an Exact Online query in the Invantive query tool?

I'm using this query:
select *
from MailMessagesReceived mmd
inner
join MailMessageAttachments mmt
on mmd.ID = mmt.ID
Where mmd.created > '2017-01-01'
And mmd.SenderMailbox = 'finappanl#lyanthe.com'
And mmd.RecipientStatusDescription = 'Prepared'
And i get a time out error without message code. It reads "Er is een time-out opgetreden voor de bewerking." The following details are attached to the error:
select * from MailMessagesReceived
inner join MailMessageAttachments
on MailMessagesReceived.ID = MailMessageAttachments.ID
Where MailMessagesReceived.created > "2017-01-01"
And MailMessagesReceived.SenderMailbox = "finappanl#lyanthe.com"
And MailMessagesReceived.RecipientStatusDescription = "Prepared"
Type: System.Net.WebException
bij System.Net.HttpWebRequest.GetResponse()
bij Invantive.Data.ODataProvider.DoRequest(HttpWebRequest request, String url, String partition, String& returnUrl, Dictionary`2& headers) in File161:regel 3666
bij Invantive.Data.ODataProvider.GetInternal(String relativeUrl, String mimeType, String partition, Boolean allowFromCache, String& returnUrl, Dictionary`2& headers, Boolean& fromCache) in File161:regel 3001
bij Invantive.Data.ODataProvider.Get[T](String relativeUrl, Dictionary`2& headers, String& fullUrl, Boolean& resultFromCache, String partition, Boolean allowFromCache, String mimeType) in File161:regel 2880
bij Invantive.Data.ODataProvider.ReadDataFromServiceResponse(List`1 rows, String basePath, List`1 allFieldTypes, String url, String partition, ObjectDefinition objectDefinition, QueryObject queryObject, Int32& pagesRetrieved, Int32& rowsRetrieved) in File161:regel 1102
bij Invantive.Data.ODataProvider.FetchDataOnePartition(String serviceUrl, String partition, List`1 rows, String basePath, List`1 allFieldTypes, ObjectDefinition objectDefinition, QueryObject queryObject, ParameterList parameters) in File161:regel 1021
bij Invantive.Data.ODataProvider.<>c__DisplayClass72_3.<Fetch>b__2(String partition) in File161:regel 877
--- Einde van stacktracering vanaf vorige locatie waar uitzondering is opgetreden ---
bij Invantive.Data.ODataProvider.Fetch(EntityFieldCollection entityFields, QueryObject queryObject, ParameterList parameters, Boolean fetchSingle, Boolean fetchCountFirst, Int32 pagingSteps, Boolean fetchCount, ResultSet& resultSet, Int32& totalNumberOfRows) in File161:regel 914
bij Invantive.Data.ExactOnlineProvider.Fetch(EntityFieldCollection entityFields, QueryObject queryObject, ParameterList parameters, Boolean fetchSingle, Boolean fetchCountFirst, Int32 pagingSteps, Boolean fetchCount, ResultSet& resultSet, Int32& totalNumberOfRows) in File298:regel 909
bij Invantive.Data.ConnectionManager.ExecuteProviderFetch(EntityFieldCollection entityFields, QueryObject queryObject, ParameterList parameters, Boolean fetchSingle, Boolean fetchCountFirst, Int32 pagingSteps, Boolean fetchCount, Int32& totalNumberOfRows, String& handlingPath) in File39:regel 3190
bij Invantive.Data.ConnectionManager.Fetch(EntityFieldCollection entityFields, QueryObject queryObject, ParameterList parameters, Boolean fetchSingle, Boolean fetchCountFirst, Int32 pagingSteps, Boolean fetchCount) in File39:regel 1406
bij Invantive.Sql.DataSourceOrFunctionTree.<GetDataFromDataContainer>d__29.MoveNext() in File120:regel 315
bij System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
bij System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
bij Invantive.Sql.FirehoseResultSet.<Iterator>d__54.MoveNext() in File133:regel 547
bij System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
bij System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
bij Invantive.Sql.FirehoseResultSet.<Iterator>d__54.MoveNext() in File133:regel 559
bij System.Linq.Buffer`1..ctor(IEnumerable`1 source)
bij System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
bij Invantive.Sql.JoinIterator.<JoinInternal>d__13.MoveNext() in File135:regel 481
bij Invantive.Sql.FilterIterator.<Iterator>d__3.MoveNext() in File132:regel 92
bij Invantive.Sql.ChainedFirehose.<Iterator>d__11.MoveNext() in File130:regel 81
bij Invantive.Sql.SelectListIterator.<Iterator>d__7.MoveNext() in File138:regel 119
bij System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
bij System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
bij Invantive.Sql.QueryPlan.Fetch() in File140:regel 91
bij Invantive.Data.ConnectionManager.ExecuteProviderPassthroughSqlActionTable(String actionSql, ParameterList parameters, String& handlingPath) in File39:regel 4033
--- Einde van stacktracering vanaf vorige locatie waar uitzondering is opgetreden ---
bij System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
bij Invantive.Data.ConnectionManager.ExecuteProviderPassthroughSqlActionTable(String actionSql, ParameterList parameters, String& handlingPath) in File39:regel 4062
bij Invantive.Data.ConnectionManager.PassthroughSqlActionTable(String actionSql, ParameterList parameters) in File39:regel 2086
--- Einde van stacktracering vanaf vorige locatie waar uitzondering is opgetreden ---
bij System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
bij Invantive.Data.ConnectionManager.PassthroughSqlActionTable(String actionSql, ParameterList parameters) in File39:regel 2098
bij Invantive.Data.ActionProceduresBase.PassthroughSqlActionTable(String actionSql, ParameterList parameters) in File29:regel 134
bij Invantive.Producer.Windows.Forms.QueryTool.ExecuteStatement(IProgressNotifier notifier, String statement, ParameterList bindVariables, Boolean showResultsInGrid, Boolean showStatistics, Boolean memorizeStatisticsInSqlHistory, Boolean allowPaging) in File948:regel 2847
bij Invantive.Producer.Windows.Forms.QueryTool.FetchResultsFromSql() in File948:regel 2430
I'm trying to get an overview of the 'Scan en Herken' (i.e. Scanning and recognition of invoices) inbox in Exact Online. This inbox contains invoices and computer generated account entries, each of which is either:
ready to be processed (green),
needs a few alterations (yellow)
or needs to be handled mannualy (red).
We want to know specifically how many invoices are in each of these three different states. For those who need alterations or manual corrections we want to know what the errors are.
With the query I was using I was just digging around to find out what data is contained in the MailMessageAttachments table. I don't know whether I'm digging in the correct place, so any advice on the subject would be nice. Furthermore I would like to know why my SQL code raises a time out.
There are some possible improvements. The REST API Mail messages (JSON) of Exact Online has recently been restructured to perform better, but nonetheless is not the fastest one around.
Please make sure first of all that you select only the divisions that you want to work with, for instance using:
use 123456,345678,56789
instead of using:
use all
Start of with a small division with some sample data and when the queries works improve performance by testing it on larger divisions.
Also, you might want to make sure that no implicit data type conversions take place, so prefer:
date-field > to_date('20170101', 'yyyymmdd')
to
date-field > '2017-01-01'
In this query it will probably not hurt.
It is better to query on status code instead of description. Descriptions vary per country and even per user. And a code might have been indexed, whereas a translatable description not.
Also, not all mail message will have an attachment, so it is better to use a left outer join.
Also, the MailMessageAttachments table can be a HUGE table (many documents included in binary format, especially when people use a gray scale or color scanner). Each row can download multiple megabytes, so it is better to only join it when absolutely needed.
Finally, you can have the query stop running after a limited number of rows have been retrieved using 'top' or 'limit' syntax.
Resulting query:
select *
from MailMessagesReceived mmd
left
outer
join MailMessageAttachments mmt
on mmd.ID = mmt.ID
Where mmd.created > to_date('20170101', 'yyyymmdd')
And mmd.SenderMailbox = 'Facturen#ExactOnline.nl' -- 'finappanl#lyanthe.com'
and mmd.recipientstatus = 20 /* Open. Etc, look up for Prepared. Enables index use. */
limit 50
When run on 30 small divisions using set requests-parallel-max 8, it takes approximately 1 minute to the row.
PS. Note that you can find the actual REST and XML URL calls and their duration using select * from exactonlinerest..sessionios.

NHibernate - HQL "join fetch" with SetMaxResults throws error

I'm trying to run the simplest query:
string queryStr = "select b " +
"from Blog b " +
"left outer join fetch b.BlogComments bc";
IList<Blog> blogs = Session.CreateQuery(queryStr)
.SetMaxResults(10)
.List<Blog>();
But it throws the following error:
System.ArgumentNullException: Value cannot be null.
Parameter name: source
However, if I remove the 'fetch' from the HQL it works fine. Also if I leave fetch in but remove SetMaxResults it also works fine. It's something to do with the fetch + SetMaxResults combination.
I'm trying to eager load child collections to optimise the query and prevent SELECT N+1 problems. I'm using NHibernate 3.3.1.4000 with a MySQL database.
My mapping:
public class BlogMap : ClassMapping<Blog>
{
public BlogMap ()
{
// other properties (snip)....
Set(x => x.BlogComments, x =>
{
x.Inverse(true);
x.Cascade(Cascade.All | Cascade.DeleteOrphans);
x.Lazy(CollectionLazy.Extra);
x.Key(k => { k.Column("BlogId"); });
}, x => x.OneToMany());
}
}
public class BlogCommentMap : ClassMapping<BlogComment>
{
public BlogCommentMap ()
{
// other properties (snip)....
ManyToOne(x => x.Blog, x =>
{
x.Column("BlogId");
x.NotNullable(true);
});
}
}
Stacktrace as requested:
[ArgumentNullException: Value cannot be null.
Parameter name: source]
System.Linq.Enumerable.ToList(IEnumerable`1 source) +4206743
NHibernate.Engine.QueryParameters.CreateCopyUsing(RowSelection selection) +178
NHibernate.Hql.Ast.ANTLR.QueryTranslatorImpl.List(ISessionImplementor session, QueryParameters queryParameters) +210
NHibernate.Engine.Query.HQLQueryPlan.PerformList(QueryParameters queryParameters, ISessionImplementor session, IList results) +369
NHibernate.Impl.SessionImpl.List(String query, QueryParameters queryParameters, IList results) +301
[GenericADOException: Could not execute query[SQL: SQL not available]]
NHibernate.Impl.SessionImpl.List(String query, QueryParameters queryParameters, IList results) +351
NHibernate.Impl.SessionImpl.List(String query, QueryParameters parameters) +282
NHibernate.Impl.QueryImpl.List() +162
WebApp.Repositories.BlogRepository.SearchBlogs(SearchBlogs search) in C:\...path...\BlogRepository.cs:43
WebApp.Controllers.HomepageController.Index(Int32 page) in C:\...path...\Controllers\HomepageController.cs:54
lambda_method(Closure , ControllerBase , Object[] ) +101
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +17
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +208
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
System.Web.Mvc.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12() +55
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +263
System.Web.Mvc.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() +19
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +191
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +343
System.Web.Mvc.Controller.ExecuteCore() +116
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +97
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10
System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +37
System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +21
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +12
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +50
System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +60
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8970061
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184
What you are experiencing is a bug... But in this case it could be a good sign! ;) Because paging (SetFirstResult(), SetMaxResults()) on a query fetching parent and its collection will be returning unexpected results. Let's say, that
DB tables contain this:
BlogA
BlogCommentA1
BlogCommentA2
BlogCommentA3
BlogB
BlogCommentB1
BlogCommentB2
QueryOver syntax (which is working) doing the same as the above HQL:
var blogs = session.QueryOver<Blog>()
.Fetch(c => c.BlogComment).Eager // collection in one SQL
.Skip(0).Take(2) // paging, but weird...
.List<Blog>();
.Skip(0).Take(2) - first page, a select resulting in this two rows but ONE BlogA:
| BlogA | BlogCommentA1
| BlogA | BlogCommentA2
.Skip(2).Take(2) - next page, weird... again BlogA
| BlogA | BlogCommentA3
| BlogB | BlogCommentB1
And this is most likely not we want.
Suggestion: go for SELECT 1+1
The most reliable in this case is doing the paging only on the parent object (Blog). And then, when we have in NHibernate session all the blogs (.Skip(2).Take(2)) we will only once call select for all their children (BlogComments).
The easiest way is set the batch-size="x", where x is a number close to the usual page size (e.g. 25 or 50).
.BatchSize(25)
NHibernate documentation 19.1.5. Using batch fetching explains details
This looks like a bug either in QueryParameters.CreateCopyUsing(), or something else is not creating the original QueryParameters correctly. Anyway, using SetMaxResults() with collection joins will force the paging to be applied client side, not in the database, which may not be what you want.
You propably want to rewrite that to use a IN on a subquery that yields 10 blog id and have the join fetching in the outer query.

Hql + SetFirstResult + SetMaxResult + Lazy Loading

I have this query
var hql = #"from Table1 tbl1
left join fetch tbl1.Table2";
var c =session.CreateQuery(hql).SetFirstResult(1).SetMaxResults(5)
.List<Table1>().ToList();
It keeps on dieing.
NHibernate.Exceptions.GenericADOException was unhandled by user code
Message=Could not execute query[SQL: SQL not available]
Source=NHibernate
SqlString=SQL not available
StackTrace:
at NHibernate.Impl.SessionImpl.List(String query, QueryParameters queryParameters, IList results)
at NHibernate.Impl.SessionImpl.List[T](String query, QueryParameters parameters)
at NHibernate.Impl.QueryImpl.List[T]()
at MvcApplication1.Controllers.Default1Controller.ThenInHql() in MvcApplication1\MvcApplication1\Controllers\Default1Controller.cs:line 152
at MvcApplication1.Controllers.Default1Controller.Index() in MvcApplication1\MvcApplication1\Controllers\Default1Controller.cs:line 21
at lambda_method(Closure , ControllerBase , Object[] )
at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)
InnerException: System.ArgumentNullException
Message=Value cannot be null.
Parameter name: source
Source=System.Core
ParamName=source
StackTrace:
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at NHibernate.Engine.QueryParameters.CreateCopyUsing(RowSelection selection)
at NHibernate.Hql.Ast.ANTLR.QueryTranslatorImpl.List(ISessionImplementor session, QueryParameters queryParameters)
at NHibernate.Engine.Query.HQLQueryPlan.PerformList(QueryParameters queryParameters, ISessionImplementor session, IList results)
at NHibernate.Impl.SessionImpl.List(String query, QueryParameters queryParameters, IList results)
InnerException:
Edit
nhibernate profiler is telling me that it is like a casting problem?
ERROR:
The value "System.Object[]" is not of type "MvcApplication1.Models.Table1" and cannot be used in this generic collection.
Parameter name: value
NHibernate ICriteria’s SetFirstResult is ZERO BASED! First Result might indicate that it starts with 1 but it doesnt. SetFirstResult(1).SetMaxResults(5) is probably not what you’re trying to do.
change it to SetFirstResult(0).SetMaxResults(5)

LINQ to SQL delete producing "Specified cast is not valid" error

I've got a painfully simple table that is giving me a "Specified cast is not valid" error when I try to delete one or more rows. The table has two columns, an "id" as the primary key (INT), and a "name" (VARCHAR(20)), which maps to a String in the LINQ to SQL dbml file. Both of these statements produce the error:
dc.DeleteOnSubmit(dc.MyTables.Where(Function(x) x.id = 1).SingleOrDefault)
dc.DeleteAllOnSubmit(dc.MyTables)
I iterated through "MyTable" just to make sure there was no weird data, and there are only two rows:
id = 1, name = "first"
id = 2, name = "second"
The exception is happening on SubmitChanges. Here is the stack trace:
[InvalidCastException: Specified cast is not valid.]
System.Data.Linq.SingleKeyManager`2.TryCreateKeyFromValues(Object[] values, V& v) +59
System.Data.Linq.IdentityCache`2.Find(Object[] keyValues) +28
System.Data.Linq.StandardIdentityManager.Find(MetaType type, Object[] keyValues) +23
System.Data.Linq.CommonDataServices.GetCachedObject(MetaType type, Object[] keyValues) +48
System.Data.Linq.ChangeProcessor.GetOtherItem(MetaAssociation assoc, Object instance) +142
System.Data.Linq.ChangeProcessor.BuildEdgeMaps() +233
System.Data.Linq.ChangeProcessor.SubmitChanges(ConflictMode failureMode) +59
System.Data.Linq.DataContext.SubmitChanges(ConflictMode failureMode) +331
System.Data.Linq.DataContext.SubmitChanges() +19
InpatientCensus.MaintenanceController.DeleteSoleCommunity(Int32 id) in C:\Documents and Settings\gregf\My Documents\Projects\InpatientCensus\InpatientCensus\Controllers\MaintenanceController.vb:14
lambda_method(ExecutionScope , ControllerBase , Object[] ) +128
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +17
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +178
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +24
System.Web.Mvc.<>c__DisplayClassa.<InvokeActionMethodWithFilters>b__7() +52
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +254
System.Web.Mvc.<>c__DisplayClassc.<InvokeActionMethodWithFilters>b__9() +19
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +192
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +399
System.Web.Mvc.Controller.ExecuteCore() +126
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +27
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +7
System.Web.Mvc.MvcHandler.ProcessRequest(HttpContextBase httpContext) +151
System.Web.Mvc.MvcHandler.ProcessRequest(HttpContext httpContext) +57
System.Web.Mvc.MvcHandler.System.Web.IHttpHandler.ProcessRequest(HttpContext httpContext) +7
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +181
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75
Removing the association added to the DBML file allows rows to be deleted. Why would the association be causing the error? The associated columns are both VARCHAR(20) in the database and resolve to Strings in the DBML file.
What could possibly be causing a casting error?
Okay, upon seeing the update, the issue is the association between your two tables. This is a known bug in .NET 3.5 SP1 and will be fixed in .NET 4.0. Try your code on a .NET 4.0 Beta if you can.
We had a similar problem, caused by using non-integer keys. Details and hotfix number are here: https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=351358
Try:
dc.MyTables.DeleteOnSubmit(dc.MyTables.SingleOrDefault(x=>x.id==1));
dc.MyTables.DeleteAllOnSubmit(dc.MyTables);