实体框架空引用异常
问题描述:
我想抓住EF代码第一,但我仍然没有得到如何从另一个类访问被引用的对象(由于缺乏足够的知识,我甚至不能制定问题)。实体框架空引用异常
这里是我的简单的代码是什么样子:
public class Destination
{
public int DestinationId { get; set; }
public string Name { get; set; }
public string Country { get; set; }
public string Description { get; set; }
public byte[] Photo { get; set; }
public List<Lodging> Lodgings { get; set; }
}
public class Lodging
{
public int LodgingId { get; set; }
public string Name { get; set; }
public string Owner { get; set; }
public bool IsResort { get; set; }
public Destination Destination { get; set; }
}
public class BreakAwayContext: DbContext
{
public DbSet<Destination> Destinations { get; set; }
public DbSet<Lodging> Lodgings { get; set; }
}
private static void InsertDestination()
{
var destination = new Destination
{
Country = "Indonesia",
Description = "EcoTourism at its best in exquisite Bali",
Name = "Bali"
};
using(var context = new BreakAwayContext())
{
context.Destinations.Add(destination);
context.SaveChanges();
}
}
private static void InsertLodging()
{
var lodging = new Lodging()
{
Name = "x",
IsResort = false,
Owner = "asdasd"
};
using(var context = new BreakAwayContext())
{
var dest = context.Destinations.Find(1);
lodging.Destination = dest;
context.Lodgings.Add(lodging);
context.SaveChanges();
}
}
private static void ShowLodgings()
{
using(var context = new BreakAwayContext())
{
foreach(var l in context.Lodgings)
{
Console.WriteLine("{0} {1} {2}", l.Name, l.Owner, l.Destination.Name);
}
}
}
我得到我尝试目的地名称写入控制台行一个NullReferenceException。
在此先感谢。
答
首先要Destination
虚拟
public virtual Destination Destination { get; set; }
然后用Include
方法
foreach(var l in context.Lodgings.Include(x => x.Destination))
+2
从性能的角度来看,'Include'可能是最好的,但是在您将Destination设置为virtual后,它将被延迟加载。 – Dabblernl 2014-09-21 21:07:07
答
只是在你的Lodging
类,virtual
设置Destination
属性。这告诉,EF在你需要时自动加载Destination
(延迟加载)。 所以你Lodging
类应该是这样的:
public class Lodging
{
public int LodgingId { get; set; }
public string Name { get; set; }
public string Owner { get; set; }
public bool IsResort { get; set; }
public virtual Destination Destination { get; set; }
}
你'没有加载Destination'。您需要启用延迟加载或使用Eager Loading。请参阅:http://msdn.microsoft.com/en-us/data/jj574232.aspx。您已经选择了正确的书籍来顺便学习Code First :-) – Dabblernl 2014-09-21 21:09:28