簡體   English   中英

實體框架Null參考異常

[英]Entity Framework Null Reference Exception

我正在嘗試先掌握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。

提前致謝。

嘗試使用navigation properties

首先將Destination 虛擬化

public virtual Destination Destination { get; set; }

然后使用Include方法

foreach(var l in context.Lodgings.Include(x => x.Destination))

只需在Lodgingvirtual設置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; }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM