Fluent NHibernate “Could not resolve property”

前端 未结 2 744
你的背包
你的背包 2021-01-04 01:10

I have read a lot of the questions about that same error but none since to match my exact problem. I\'m trying to access the property of an object, itself part of a root obj

2条回答
  •  梦谈多话
    2021-01-04 01:32

    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()
                   .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()
                   .Where(al => al.Name == albumName)
               .JoinQueryOver(al => al.Artist)
                   .Where(ar => ar.Name == artistName)
               .Take(1)
               .SingleOrDefault();
    

提交回复
热议问题