我刚开始使用nHibernate Fluent,并且我的关联一切顺利,直到我找到一个具有null的StateID(外键,见下文)的位置。然后我收到错误“空引用异常”
此行 Console.WriteLine(location.address +“,”+ 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中可能不应该为null。 StateID是states表上ID的外键,所以我想不应该允许它为null?
无论如何,我觉得我的代码应该能够允许这种或那种方式,所以我该如何解决这个问题呢?
答案 0 :(得分:1)
Console.WriteLine(location.address + ", " + (location.State == null ? "Unknown" : location.State.state));