流畅的 nhibernate 可空外键“空引用异常”
我刚刚开始使用 nHibernate Fluent,并且我的关联一切进展顺利,直到我遇到一个 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; }
}
我猜该值在数据库中可能不应该为空。 StateID是states表上ID的外键,所以我想它不应该允许为空?
无论如何,我觉得我的代码应该能够以某种方式允许这种情况,那么我该如何解决这个问题呢?
I have just started with nHibernate Fluent and all is going well with my associations, until I hit a location that have a StateID (which is a foreign key, see below) of null. Then I get an error "null reference exception"
on this line Console.WriteLine(location.address + ", " + location.State.state);
below:
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; }
}
I guess this value might shouldn't probably be null in the DB. StateID is a foreign key to ID on the states table, so I guess it shouldn't be allowed to be null?
Anyway I feel that my code should be able to allow for this one way or another, so how can I get around this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)