1

我正在使用带有 EF 代码优先方法的 MVC 4。我有两个简单的对象。这些是他们的 POCO 课程:

public class Activity
{
        //Primitive Properties
        [HiddenInput]
        public int Id { get; set; }

        [Required]
        public int LengthInMinutes { get; set; }

        public string AdditionalInfo { get; set; }

        [Required]
        public bool Archive { get; set; }

        //Navigation Properties
        public virtual User User { get; set; }
        public virtual ActivitySet ActivitySet { get; set; }
        public virtual ICollection<Company> Companies { get; set; }
        public virtual ICollection<Description> Descriptions { get; set; }
}

public class Company
{
        //Primitive Properties
        [HiddenInput]
        public int Id { get; set; }

        [Required]
        public string Title { get; set; }

        [Required]
        public bool Archive { get; set; }

        //Navigation Properties
        public virtual ICollection<Activity> Activities { get; set; }
}

因此 Activity 和 Company 实体之间存在多对多的关系。我正在我的存储库类中创建新活动,但是当我为活动分配公司时,如下所示:

activity.Companies.Add(company);

我得到 NullReference 异常。我环顾四周,但根据此链接:

BuildStarted.com

我的方法似乎是正确的。

为什么它不起作用???

4

1 回答 1

0

在您可以使用 Add() off Companies 之前,需要对其进行初始化。

activity.Companies = new List<Company>();

您也可以在 Activity 的构造函数中对其进行初始化。

public class Activity
{
    public Activity()
    {
        Companies = new List<Company>();
        Descriptions = new List<Description>();
    }

    //Primitive Properties
    [HiddenInput]
    public int Id { get; set; }

    [Required]
    public int LengthInMinutes { get; set; }

    public string AdditionalInfo { get; set; }

    [Required]
    public bool Archive { get; set; }

    //Navigation Properties
    public virtual User User { get; set; }
    public virtual ActivitySet ActivitySet { get; set; }
    public virtual ICollection<Company> Companies { get; set; }
    public virtual ICollection<Description> Descriptions { get; set; }
}
于 2012-11-21T15:59:14.487 回答