在EF中设置“有多个,通过”时,对象引用未设置为对象的实例

时间:2014-09-25 04:23:55

标签: c# entity-framework nullreferenceexception

我正在尝试使用实体框架和Fluent API设置Has many, through关系。

这个项目涉及洗车。可以为每个位置设置清洗菜单,每个菜单可以分配多个包。包也可以分配给多个菜单。

public class WashMenu
{
    [Key, ForeignKey("Location")]
    public int ID { get; set; }

    public virtual Location Location { get; set; }
    public virtual ICollection<WashPackage> Packages { get; set; }
}

public class WashPackage
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string InternalName { get; set; }

    public virtual ICollection<WashMenu> Menus { get; set; }
}

这是通过像这样的流畅的API映射的......

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<WashMenu>().
       HasMany(c => c.Packages).
       WithMany().
       Map(
        m =>
        {
            m.MapLeftKey("WashMenu_id");
            m.MapRightKey("WashPackage_id");
            m.ToTable("WashMenuPackages");
        });
}

并像这样初始化......

protected override void Seed(MightyWashContext context)
{
    var locations = new List<Location>
    {
        new Location { Name="Super Awesome Car Wash", Address="82nd and Milwaukee", PhoneNumber="806.555.1234", HoursOfOperation="8:00-9:00", Manager="Bob Mills" }
    };
    locations.ForEach(i => context.Locations.Add(i));
    context.SaveChanges();

    var washPackages = new List<WashPackage>
    {
        new WashPackage { Name = "Wonder Wash" },
        new WashPackage { Name = "Super Wash" },               
        new WashPackage { Name = "Mighty Wash" }
    };
    washPackages.ForEach(i => context.WashPackages.Add(i));
    context.SaveChanges();

    var washMenus = new List<WashMenu>
    {
        new WashMenu { Location = locations.First() }
    };

    washMenus.First().Packages.Add(context.WashPackages.First());
    washMenus.First().Packages.Add(context.WashPackages.Last());

    washMenus.ForEach(i => context.WashMenus.Add(i));
    context.SaveChanges();
}

问题

每当我尝试初始化数据库(即构建和运行)时,都会抛出异常:

An exception of type 'System.NullReferenceException' occurred in {my_app}.dll but was not handled in user code

Additional information: Object reference not set to an instance of an object.

这是有问题的一行。

washMenus.First().Packages.Add(context.WashPackages.First());

是什么给出了?

0 个答案:

没有答案