我对NHibenate有疑问。当我运行查询时,我收到错误“无法解析属性:User.Name of:MegaOnlineChat.Core.Entities.Message”。我做错了什么?
实体对象
public class EntityObject<TId>
{
public virtual Int32 Id { get; set; }
}
public class User:EntityObject<Int32>
{
public virtual String Name { get; set; }
public virtual String Password { get; set; }
public virtual Boolean Admin { get; set; }
public virtual IList<Message> Messages { get; set; }
}
public class Message:EntityObject<Int32>
{
public virtual String Text { get; set; }
public virtual User User { get; set; }
public virtual DateTime Date{ get; set; }
}
映射
public class UserMapping:ClassMap<User>
{
public UserMapping()
{
Table("Users");
Id(m => m.Id).GeneratedBy.Native();
Map(m => m.Name).Unique().Not.Nullable();
Map(m => m.Admin).Not.Nullable();
Map(m => m.Password).Not.Nullable();
HasMany(m => m.Messages).KeyColumn("User_id");
}
}
public class MessageMapping:ClassMap<Message>
{
public MessageMapping()
{
Table("Messages");
Id(m => m.Id).GeneratedBy.Native();
Map(m => m.Text).Not.Nullable();
Map(m => m.Date).Not.Nullable();
References(m => m.User, "User_id").Not.Nullable();
}
}
QueryOver
NHibernateSession.QueryOver<Message>().Where(x => x.User.Name == name).List<Message>().Last();
答案 0 :(得分:18)
QueryOver与Linq查询提供程序不同。这样做会更容易:
NHibernateSession.Query<Message>().Where(x => x.User.Name == name).ToList();
但是如果你想使用QueryOver,你需要明确地加入你想要导航的关系:
NHibernateSession.QueryOver<Message>()
.JoinQueryOver(x => x.User) // navigate to the user on the relationship
.Where(u => u.Name == name) // this restriction is on the User now
.List();
您也可以使用用户的别名
来执行此操作