在MVC 4中创建具有多对多关系的对象

时间:2012-11-21 15:52:35

标签: asp.net-mvc entity-framework many-to-many

我正在使用MVC 4和EF代码第一种方法。我有两个简单的对象。这些是他们的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,但是当我像这样为Activity分配公司时:

activity.Companies.Add(company);

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

BuildStarted.com

我的做法似乎是正确的。

为什么不起作用?

1 个答案:

答案 0 :(得分:0)

在使用公司的Add()之前,需要对其进行初始化。

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; }
}