我想抓住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'。您需要啓用延遲加載或使用Eager Loading。請參閱:http://msdn.microsoft.com/en-us/data/jj574232.aspx。您已經選擇了正確的書籍來順便學習Code First :-) – Dabblernl 2014-09-21 21:09:28