繁体   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