Fluent NHibernate “Could not resolve property”

倖福魔咒の 提交于 2019-11-30 17:43:19

You have to think of your QueryOver query as (nearly) directly translating into SQL. With this in mind, imagine this SQL query:

select
    Album.*
from
    Album
where
    Album.Name = 'SomeAlbumName' and
    Album.Artist.Name = 'SomeArtistName'

This won't work because you can't access a related table's properties like that in a SQL statement. You need to create a join from Album to Artist and then use a Where clause:

var riAlbum = 
    session.QueryOver<Album>()
               .Where(al => al.Name == albumName)
           .JoinQueryOver(al => al.Artist)
               .Where(ar => ar.Name == artistName)
           .List()
           .FirstOrDefault();

Also, since you're using FirstOrDefault, you may want to consider moving that logic to the database end. Currently, you're pulling back every record matching your criteria and then taking the first one. You could use .Take to limit the query to 1 result:

var riAlbum = 
    session.QueryOver<Album>()
               .Where(al => al.Name == albumName)
           .JoinQueryOver(al => al.Artist)
               .Where(ar => ar.Name == artistName)
           .Take(1)
           .SingleOrDefault<Album>();

Another explanation is that you are missing your mapping of this property or field in a NHibernateClassMapping definition. I came here about why I was getting this error based on the following scenario.

 var query = scheduleRepository.CurrentSession().Query<Schedule>()
                .Where(x => x.ScheduleInfo.StartDate.Date < dateOfRun.Date);

This was giving me a Could Not Resolve Property error for StartDate. This was a head scratcher, since I use this syntax all the time.

My mapping file was the following:

public class ScheduleInfoMapping : NHibernateClassMapping<ScheduleInfo>
    {
        public ScheduleInfoMapping()
        {
            DiscriminateSubClassesOnColumn("Type");
            Map(x => x.Detail).MapAsLongText();
        }
    }

which was missing the StartDate. Changed to:

public class ScheduleInfoMapping : NHibernateClassMapping<ScheduleInfo>
    {
        public ScheduleInfoMapping()
        {
            DiscriminateSubClassesOnColumn("Type");
            Map(x => x.Detail).MapAsLongText();
            Map(x => x.StartDate);
        }
    }

Which resolved the error.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!