System.InvalidCastException: Specified cast is not valid. Fluent NHibernate and C#

1,079 views
Skip to first unread message

Jamie D

unread,
Jul 15, 2016, 3:04:45 PM7/15/16
to nhusers

I am not able to find anything to help me figure out the problem with my `specified cast is not valid` error. I have been researching to find a solution, but it doesn't seem like there are any answers valid to what is going on with my code. I can't run this in Visual Studio locally because it is showing that it works. Locally, I have it pointed to the same database that the live site is using, so I know it's not an error with the database. I have checked the values in the database and all the data looks to be fine. The main NHibernate programmer here in the office can't even figure out what the heck is going on. He ran the sln on his computer and it worked locally for him as well. Publishing to the live site is where the trouble comes in. I've tried comparing the web.config in my local copy to the one on the server and they are identical! Any help is appreciated.

   [InvalidCastException: Specified cast is not valid.]
    (Object , Object[] , SetterCallback ) +2556
    NHibernate.Tuple.Entity.PocoEntityTuplizer.SetPropertyValuesWithOptimizer(Object entity, Object[] values) +80

    [PropertyAccessException: Invalid Cast (check your mapping for property type mismatches); setter of Showroom.Vehicle]
    NHibernate.Tuple.Entity.PocoEntityTuplizer.SetPropertyValuesWithOptimizer(Object entity, Object[] values) +207
    NHibernate.Engine.TwoPhaseLoad.InitializeEntity(Object entity, Boolean readOnly, ISessionImplementor session, PreLoadEvent preLoadEvent, PostLoadEvent postLoadEvent) +989
    NHibernate.Loader.Loader.InitializeEntitiesAndCollections(IList hydratedObjects, Object resultSetId, ISessionImplementor session, Boolean readOnly) +441
    NHibernate.Loader.Loader.DoQuery(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies) +1157
    NHibernate.Loader.Loader.DoQueryAndInitializeNonLazyCollections(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies) +205
    NHibernate.Loader.Loader.DoList(ISessionImplementor session, QueryParameters queryParameters) +425
    NHibernate.Loader.Loader.ListIgnoreQueryCache(ISessionImplementor session, QueryParameters queryParameters) +23
    NHibernate.Hql.Ast.ANTLR.Loader.QueryLoader.List(ISessionImplementor session, QueryParameters queryParameters) +99
    NHibernate.Hql.Ast.ANTLR.QueryTranslatorImpl.List(ISessionImplementor session, QueryParameters queryParameters) +494
    NHibernate.Engine.Query.HQLQueryPlan.PerformList(QueryParameters queryParameters, ISessionImplementor session, IList results) +743
    NHibernate.Impl.SessionImpl.List(IQueryExpression queryExpression, QueryParameters queryParameters, IList results) +675
    NHibernate.Impl.AbstractSessionImpl.List(IQueryExpression queryExpression, QueryParameters parameters) +235
    NHibernate.Impl.ExpressionQueryImpl.List() +189
    NHibernate.Linq.DefaultQueryProvider.ExecuteQuery(NhLinqExpression nhLinqExpression, IQuery query, NhLinqExpression nhQuery) +61
    NHibernate.Linq.DefaultQueryProvider.Execute(Expression expression) +262
    NHibernate.Linq.DefaultQueryProvider.Execute(Expression expression) +26
    Remotion.Linq.QueryableBase`1.GetEnumerator() +83
    System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) +446
    System.Linq.Enumerable.ToList(IEnumerable`1 source) +80
    Repository.Showroom.VehicleRepository.GetAll(Int32 siteID, Boolean active) in \Repository\Showroom\VehicleRepository.cs:52
    Showroom.Catalog_Maintenance.VehicleGrid_NeedDataSource(Object source, GridNeedDataSourceEventArgs e) in \Showroom\Catalog-Maintenance.aspx.cs:36
    Telerik.Web.UI.RadGrid.OnNeedDataSource(GridNeedDataSourceEventArgs e) +191
    Telerik.Web.UI.RadGrid.AutoDataBind(GridRebindReason rebindReason) +109
    Telerik.Web.UI.RadGrid.OnLoad(EventArgs e) +224
    System.Web.UI.Control.LoadRecursive() +71
    System.Web.UI.Control.LoadRecursive() +190
    System.Web.UI.Control.LoadRecursive() +190
    System.Web.UI.Control.LoadRecursive() +190
    System.Web.UI.Control.LoadRecursive() +190
    System.Web.UI.Control.LoadRecursive() +190
    System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3178

Here is the code it is referencing:

line 52 of VehicleRepository:

return this.GetQuery().Where(x => x.Active == active && x.Site.ID == siteID).ToList();
    

GetQuery looks like this:

public IQueryable<T> GetQuery()
{
    return this.Session.Query<T>(); 
}  

line 36 of Catalog-Maintenance:

var vehicles = _VehicleRepository.GetAll(SiteID, true);

here is my Vehicle Map

public class VehicleMap : OrderedEntityClassMap<Vehicle, Int32>
    {
        public VehicleMap()
        {
            Schema("Showroom"); 

            Map(x => x.Name);
            Map(x => x.Make);
            Map(x => x.Model);
            Map(x => x.BodyStyle);
            Map(x => x.Engine);
            Map(x => x.DriveType);
            Map(x => x.Transmission);
            Map(x => x.StockNumber);
            Map(x => x.ExteriorColor);
            Map(x => x.InteriorColor);
            Map(x => x.Warranty);
            Map(x => x.Price);
            Map(x => x.Vin);
            Map(x => x.Mileage);
            Map(x => x.Year);
            Map(x => x.Description);
            Map(x => x.Options);
            Map(x => x.Specs);
            Map(x => x.Active);
            Map(x => x.DateCreated);
            Map(x => x.LastUpdated);
            References(x => x.Site, "SiteID").LazyLoad();

            HasMany(x => x.Photos)
                .KeyColumn("VehicleID")
                .Cascade.AllDeleteOrphan()
                .LazyLoad()
                .Inverse();
        }
    }

Gunnar Liljas

unread,
Jul 15, 2016, 6:40:51 PM7/15/16
to nhu...@googlegroups.com
You say you've run it against the same database, but have you looked at exactly the same data?

It seems the data doesn't quite match the property types. Maybe you have an int property and the database returns NULL? 

Although it's not likely relevant, the LazyLoad mapping instructions are redundant. Lazy=true is the default.

/G 

Jamie D

unread,
Jul 18, 2016, 11:47:19 AM7/18/16
to nhusers
That's the weird part, the data matches the database values correctly and mostly everything is nullable types so labeled as int? in the mapping. I've had the NHibernate guru in the office look at this too and he doesn't see where the issue is either. The db looks like this:

ID              int            not nullable
SiteID          smallint       not nullable
Name            varchar(200)   not nullable
Make            varchar(50)    allow nulls
Model           varchar(200)   allow nulls
BodyStyle       varchar(100)   allow nulls
Engine          varchar(100)   allow nulls
DriveType       varchar(50)    allow nulls
Transmission    varchar(50)    allow nulls
StockNumber     varchar(50)    allow nulls
ExteriorColor   varchar(100)   allow nulls
InteriorColor   varchar(100)   allow nulls
Warranty        varchar(MAX)   allow nulls
Price           decimal (19,2) allow nulls
VIN             varchar
(100)   allow nulls
Mileage         int            allow nulls
Year            varchar(50)    allow nulls
Description     varchar(MAX)   allow nulls
Options         varchar(MAX)   allow nulls
Specs           varchar(MAX)   allow nulls
[Order]         int not        nullable
Active          bit not        nullable
LastUpdated     datetime       not nullable
DateCreated     datetime       not nullable

I've even tried deleting the last couple items that were added to the database in the past couple weeks and it doesn't seem to help. I will keep looking but I'm stumped with this one.

Oskar Berggren

unread,
Jul 18, 2016, 2:44:44 PM7/18/16
to nhu...@googlegroups.com

The exception mentions ShowRoom.Vehicle property setter. Have you followed up what's going on in there? And it's mapping?

/Oskar

--
You received this message because you are subscribed to the Google Groups "nhusers" group.
To unsubscribe from this group and stop receiving emails from it, send an email to nhusers+u...@googlegroups.com.
To post to this group, send email to nhu...@googlegroups.com.
Visit this group at https://groups.google.com/group/nhusers.
For more options, visit https://groups.google.com/d/optout.

Jamie D

unread,
Jul 18, 2016, 5:23:06 PM7/18/16
to nhusers
Yeppers. This isn't making any sense as to why it isn't working all of a sudden. We are ditching NHibernate on these pages and using stored procedures instead. Thank you all for the help!

Andreas Ravnestad

unread,
Jul 19, 2016, 10:19:34 AM7/19/16
to nhusers
Since this seems to be an ASP.Net application, make sure that there are no redundant assemblies floating around in the bin directory on the live site. If you rename an assembly and don't remove the old version weird stuff like this can happen.
Reply all
Reply to author
Forward
0 new messages