实体框架空引用异常

时间:2014-09-21 17:46:30

标签: c# entity-framework ef-code-first

我正在尝试掌握EF Code First,但我仍然不知道如何从另一个类访问引用的对象(由于缺乏足够的知识,我甚至无法提出问题)。

以下是我的简单代码:

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。

提前致谢。

2 个答案:

答案 0 :(得分:1)

尝试使用navigation properties

首先制作Destination 虚拟

public virtual Destination Destination { get; set; }

然后使用Include方法

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

答案 1 :(得分:0)

只需在Destination班级Lodging中设置virtual媒体资源即可。这告诉,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; }
}