【问题标题】:Entity Framework Null Reference Exception实体框架空引用异常
【发布时间】: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。

提前致谢。

【问题讨论】:

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


【解决方案1】:

尝试使用navigation properties

首先使Destination虚拟

public virtual Destination Destination { get; set; }

然后使用Include方法

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

【讨论】:

  • 从性能角度来看,Include 可能是最好的,但在你创建了 Destination virtual 之后,它将被延迟加载。
【解决方案2】:

只需在您的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; }
}

【讨论】:

    猜你喜欢
    • 2018-09-13
    • 1970-01-01
    • 2016-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-18
    相关资源
    最近更新 更多