2014-09-21 108 views
0

我想抓住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。

在此先感謝。

+0

你'沒有加載Destination'。您需要啓用延遲加載或使用Eager Loading。請參閱:http://msdn.microsoft.com/en-us/data/jj574232.aspx。您已經選擇了正確的書籍來順便學習Code First :-) – Dabblernl 2014-09-21 21:09:28

回答

1

嘗試使用navigation properties

首先要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

0

只是在你的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; } 
}