Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 957535
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 16, 20262026-05-16T00:43:08+00:00 2026-05-16T00:43:08+00:00

(Edited to avoid leading down the wrong road) Before giving details, very short version:

  • 0

(Edited to avoid leading down the wrong road)

Before giving details, very short version: I have a SQL statement I need to get out of NHibernate, and I have Criteria API statements that give it to me. The NHibernate is trying to do something wrong with the statement it generates, and I’m trying to figure out why.

I have the following mappings in Fluent NHibernate:

public class StaffClass {
    public virtual int Staff_DBID { get; private set; }
    public virtual int Class_DBID { get; private set; }

    // Equals and GetHasCode overrides not shown
    // other code originally here removed as it was distracting from the point and didn't change anything
}

public class StaffClassMap : ClassMap<StaffClass> {
    public StaffClassMap() {
        CompositeId()
            .KeyProperty(x => x.Staff_DBID)
            .KeyProperty(x => x.Class_DBID);
    }
}

A similar set of code is present for a table named ClassStudent. Both of these tables are join tables.

I have the following code that runs against domain objects:

            using (transaction = session.BeginTransaction()) {

                var criteria = session.CreateCriteria(typeof(Student));

                var staffClasses = DetachedCriteria.For<StaffClass>()
                    .Add(Restrictions.Eq("Staff_DBID", desiredStaffDBID))
                    .SetProjection(Projections.Property("Class_DBID"));

                var studentClasses = DetachedCriteria.For<ClassStudent>()
                    .Add(Subqueries.In("Class_DBID", staffClasses))
                    .SetProjection(Projections.Property("Student_DBID"));

                criteria.Add(Subqueries.In("Student_DBID", studentClasses));

                var students = criteria.List<Student>();

                foreach (var student in students) {
                    Console.WriteLine(string.Format("Student: {0}, {1}", student.LastName, student.FirstName));
                }
            }

When I attempt to run this code, I get the following exception back:

NHibernate.ADOException occurred
  Message=could not execute query
[ SELECT this_.Student_DBID as Student1_7_0_, this_.DistrictStudentID as District2_7_0_, this_.LastName as LastName7_0_, this_.FirstName as FirstName7_0_, this_.MidName as MidName7_0_, this_.School_DBID as School6_7_0_ FROM [Student] this_ WHERE @p0 in (SELECT this_0_.Student_DBID as y0_ FROM [ClassStudent] this_0_ WHERE @p1 in (SELECT this_0_0_.Class_DBID as y0_ FROM [StaffClass] this_0_0_ WHERE this_0_0_.Staff_DBID = @p2)) ]
Positional parameters:  #0>Student_DBID #1>Class_DBID #2>3664
[SQL: SELECT this_.Student_DBID as Student1_7_0_, this_.DistrictStudentID as District2_7_0_, this_.LastName as LastName7_0_, this_.FirstName as FirstName7_0_, this_.MidName as MidName7_0_, this_.School_DBID as School6_7_0_ FROM [Student] this_ WHERE @p0 in (SELECT this_0_.Student_DBID as y0_ FROM [ClassStudent] this_0_ WHERE @p1 in (SELECT this_0_0_.Class_DBID as y0_ FROM [StaffClass] this_0_0_ WHERE this_0_0_.Staff_DBID = @p2))]
  Source=NHibernate
  SqlString=SELECT this_.Student_DBID as Student1_7_0_, this_.DistrictStudentID as District2_7_0_, this_.LastName as LastName7_0_, this_.FirstName as FirstName7_0_, this_.MidName as MidName7_0_, this_.School_DBID as School6_7_0_ FROM [Student] this_ WHERE @p0 in (SELECT this_0_.Student_DBID as y0_ FROM [ClassStudent] this_0_ WHERE @p1 in (SELECT this_0_0_.Class_DBID as y0_ FROM [StaffClass] this_0_0_ WHERE this_0_0_.Staff_DBID = @p2))
  StackTrace:
       at NHibernate.Loader.Loader.DoList(ISessionImplementor session, QueryParameters queryParameters)
       at NHibernate.Loader.Loader.ListIgnoreQueryCache(ISessionImplementor session, QueryParameters queryParameters)
       at NHibernate.Loader.Loader.List(ISessionImplementor session, QueryParameters queryParameters, ISet`1 querySpaces, IType[] resultTypes)
       at NHibernate.Loader.Criteria.CriteriaLoader.List(ISessionImplementor session)
       at NHibernate.Impl.SessionImpl.List(CriteriaImpl criteria, IList results)
       at NHibernate.Impl.CriteriaImpl.List(IList results)
       at NHibernate.Impl.CriteriaImpl.List[T]()
       at Test.Program.Main(String[] args) in C:\Projects\Test\Test\Program.cs:line 86
  InnerException: System.FormatException
       Message=Failed to convert parameter value from a String to a Int32.
       Source=System.Data
       StackTrace:
            at System.Data.SqlClient.SqlParameter.CoerceValue(Object value, MetaType destinationType)
            at System.Data.SqlClient.SqlParameter.GetCoercedValue()
            at System.Data.SqlClient.SqlParameter.Validate(Int32 index, Boolean isCommandProc)
            at System.Data.SqlClient.SqlCommand.BuildParamList(TdsParser parser, SqlParameterCollection parameters)
            at System.Data.SqlClient.SqlCommand.BuildExecuteSql(CommandBehavior behavior, String commandText, SqlParameterCollection parameters, _SqlRPC& rpc)
            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.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
            at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
            at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
            at System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader()
            at NHibernate.AdoNet.AbstractBatcher.ExecuteReader(IDbCommand cmd)
            at NHibernate.Loader.Loader.GetResultSet(IDbCommand st, Boolean autoDiscoverTypes, Boolean callable, RowSelection selection, ISessionImplementor session)
            at NHibernate.Loader.Loader.DoQuery(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies)
            at NHibernate.Loader.Loader.DoQueryAndInitializeNonLazyCollections(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies)
            at NHibernate.Loader.Loader.DoList(ISessionImplementor session, QueryParameters queryParameters)
       InnerException: System.FormatException
            Message=Input string was not in a correct format.
            Source=mscorlib
            StackTrace:
                 at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
                 at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
                 at System.String.System.IConvertible.ToInt32(IFormatProvider provider)
                 at System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider)
                 at System.Data.SqlClient.SqlParameter.CoerceValue(Object value, MetaType destinationType)

What’s annoying me right now the most is that the generated SQL is exactly what I want the SQL to look like. If I run the SQL in SQL Server Managmeent Studio (SQL 2008) with manual parameter replacement I get a correct result set:

SELECT
    this_.Student_DBID as Student1_7_0_, 
    this_.DistrictStudentID as District2_7_0_, 
    this_.LastName as LastName7_0_, 
    this_.FirstName as FirstName7_0_, 
    this_.MidName as MidName7_0_, 
    this_.School_DBID as School6_7_0_ 
FROM
    [Student] this_ 
WHERE 
    Student_DBID in (
        SELECT 
            this_0_.Student_DBID as y0_ 
        FROM
            [ClassStudent] this_0_ 
        WHERE Class_DBID in (
            SELECT
                this_0_0_.Class_DBID as y0_ 
            FROM
                [StaffClass] this_0_0_ 
            WHERE
                this_0_0_.Staff_DBID = 3664
        )
    )

Where is the attempted parameter conversion coming from? Why is it happening? And what can I do to avoid the issue?

Thanks!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-16T00:43:08+00:00Added an answer on May 16, 2026 at 12:43 am

    Just to close this question off – I gave up on convincing NHibernate to do what I wanted. I decided instead to use General SQL Parser and a wrapper around the real command and connection providers. A similar task for a different reason is described at http://blog.theagileworkshop.com/2009/06/09/using-schemas-with-sqlite-for-in-memory-nhibernate-tests/. In any event, this avoids the whole issue because it forces me to work at the SQL level, which ot only lets me do what I want without NHibernate getting in the way but also allows HQL and even direct DB access to be intercepted.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.