流畅的非hibernate可空外键“空引用异常”
本文关键字:引用 异常 空引用异常 hibernate | 更新日期: 2023-09-27 18:15:36
我刚刚开始使用nHibernate Fluent,我的关联都很顺利,直到我碰到一个位置,它的StateID(这是一个外键,见下文)为null。然后我得到一个错误"null reference exception"
Console.WriteLine(location。地址 + ", " + location.State.state);:
public static void LoadLocationsFromDatabase()
{
using (var session = NHibernateHelper.OpenSession())
{
// retreive all stores and display them
using (session.BeginTransaction())
{
var locations = session.CreateCriteria(typeof(Location))
.List<Location>();
var i = 0;
foreach (var location in locations)
{
i++;
Console.WriteLine(location.address + ", " + location.State.state);
}
}
}
}
public LocationMap()
{
Id(x => x.locationID).Column("ID");
Map(x => x.address).Column("Address");
References(x => x.State)
.Column("StateID")
.Cascade.All();
}
public class State
{
public virtual int ID { get; set; }
public virtual String state { get; set; }
public virtual IList<Location> Locations { get; set; }
}
我猜这个值可能不应该在DB中为空。StateID是状态表上ID的外键,所以我猜它不应该是空的?
无论如何,我觉得我的代码应该能够允许这样或那样的方式,那么我怎么才能绕过这个呢?Console.WriteLine(location.address + ", " + (location.State == null ? "Unknown" : location.State.state));