问题描述
我已经读了很多关于同样的错误问题,但由于没有符合我确切的问题。我试图访问一个对象的属性,根对象自身的一部分,用流利的NHibernate的。一些答案说,我需要用预测,别人说我需要使用加入,我觉得应该通过延迟加载工作。
下面是我的两个班的一起流利的映射:
艺术家级
公共类艺术家
{
公共虚拟INT标识{搞定;组; }
公共虚拟字符串名称{;组; }
公共虚拟的IList<相册和GT;相册{搞定;组; }
公共虚拟字符串MusicBrainzId {搞定;组; }
公共虚拟字符串TheAudioDbId {搞定;组; }
公共艺术家(){}
}
公共类ArtistMap:ClassMap<艺术家>
{
公共ArtistMap()
{
LazyLoad();
ID(A => a.Id);
地图(A => a.Name)的.index(姓名);
的hasMany(A => a.Albums)
.Cascade.All();
地图(A => a.MusicBrainzId);
地图(A => a.TheAudioDbId);
}
}
专辑类
公共类专辑
{
公共虚拟INT标识{搞定;组; }
公共虚拟艺术家艺术家{搞定;组; }
公共虚拟字符串名称{;组; }
公共虚拟的IList<轨道>曲目{搞定;组; }
公共虚拟的DateTime RELEASEDATE {搞定;组; }
公共虚拟字符串TheAudioDbId {搞定;组; }
公共虚拟字符串MusicBrainzId {搞定;组; }
公共相册(){}
}
公共类AlbumMap:ClassMap<相册和GT;
{
公共AlbumMap()
{
LazyLoad();
ID(A => a.Id);
引用(A => a.Artist)
.Cascade.All();
地图(A => a.Name)的.index(姓名);
的hasMany(A => a.Tracks)
.Cascade.All();
地图(A => a.ReleaseDate);
地图(A => a.TheAudioDbId);
地图(A => a.MusicBrainzId);
}
}
当这段代码被解释发生错误:
VAR riAlbum = session.QueryOver<相册和GT;()
。凡(X => x.Name == ALBUMNAME&功放;&安培; x.Artist.Name ==艺术家)
的.List()FirstOrDefault()。
在功能NHibernate尝试解析x.Artist.Name值发生错误:
What would be the correct way of doing this?
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>();
这篇关于功能NHibernate"无法解析财产"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!