【发布时间】:2014-09-25 14:18:11
【问题描述】:
我正在尝试首先掌握 EF Code,但我仍然不知道如何从另一个类访问引用的对象(由于缺乏足够的知识,我什至无法提出问题。
我的简单代码如下所示:
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未加载。您需要启用延迟加载或使用急切加载。请参阅:msdn.microsoft.com/en-us/data/jj574232.aspx。顺便说一句,您选择了正确的书来学习 Code First :-)
标签: c# entity-framework ef-code-first