[英]Entity Framework Null Reference Exception
I am trying to grasp EF Code First but I still do not get how to access the referenced objects from another class (due to lack of enough knowledge, I cannot even formulate the question). 我正在尝试先掌握EF Code,但仍然不知道如何从另一个类访问被引用的对象(由于缺乏足够的知识,我什至无法提出问题)。
Here's what my simple code looks like: 这是我的简单代码:
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);
}
}
}
I get a NullReferenceException on the line I try to write the destination name to the console. 我在尝试将目标名称写入控制台的那一行上收到NullReferenceException。
Thanks in advance. 提前致谢。
Try using navigation properties
: 尝试使用navigation properties
:
First make Destination
virtual 首先将Destination
虚拟化
public virtual Destination Destination { get; set; }
Then use Include
method 然后使用Include
方法
foreach(var l in context.Lodgings.Include(x => x.Destination))
Just set Destination
property in your Lodging
class, virtual
. 只需在Lodging
类virtual
设置Destination
属性。 This tell, the EF to load Destination
automatically when you need it(Lazy Loading). 这表明,EF在需要时自动加载Destination
(延迟加载)。 So your Lodging
class should looks like: 因此,您的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; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.