System.NullReferenceException 在 entity framework 中为多对多关系插入新项目时

System.NullReferenceException when Inserting a new item for many-to-many relationship in entity framework

为多对多关系添加项目时,我收到此错误

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

没有进一步的细节。

抛出异常的代码如下:

protected void btn_AddMembers_Click(object sender, EventArgs e)
{
        gEchoLuDBContext _db = new gEchoLuDBContext();
        int wallId = Convert.ToInt32(grd_Walls.SelectedDataKey.Value);

        DiscussionWall selectedWall = _db.DiscussionWalls.Single(dw => dw.WallId == wallId);

        foreach (ListItem item in cbList_AllMembers.Items)
        {
            if (item.Selected)//if the checkbox item (i.e., user) is selected
            {
                Person selectedPerson = _db.People.Single(p => p.Id == item.Value.ToString());
//then retrieve the user from db

                selectedWall.Members.Add(selectedPerson);//**this line throws the error**
//add user to the selected wall
            }
        }

        _db.SaveChanges();

        BindWallMembers();
}

在上面的代码中,当我调试它时,我看到 none 个实例(selectedWallselectedPerson)为空。下面是相关类的相关章节以及它们之间的关系:

public class DiscussionWall
{
    [Key]
    public int WallId { get; set; }

    public List<Person> Members { get; set; }
}

[Table("AspNetUsers")]
public class Person : IdentityUser
{
    public List<Course> RegisteredCourses { get; set; }
    public List<DiscussionWall> AttendedDiscussionWalls { get; set; }
}

流利api代码:

modelBuilder.Entity<DiscussionWall>()
            .HasMany(dw => dw.Members)
            .WithMany(p => p.AttendedDiscussionWalls)
            .Map(m => m.MapLeftKey("WallId").MapRightKey("Id")
            .ToTable("EnrollmentsToDiscussionWalls"));

有谁知道我的逻辑和代码有什么问题吗?

看起来 DiscussionWall.Members 为空。您的代码未将其初始化为任何内容。尝试:

private List<Person> _members;
public List<Person> Members
{
  get { return _members ?? (_members = new List<Person>()); }
  set { _members = value; }
}

另请参阅:Why is my Entity Framework Code First proxy collection null and why can't I set it?