添加具有实体框架多对多关系的项目时,“对象引用未设置为对象错误的实例”

时间:2015-03-01 05:25:21

标签: c# linq entity-framework many-to-many

我有一个错误,我不知道,因为它没有提供任何细节,除了说对象引用没有设置为对象错误的实例。我在Person和Course类之间有多对多的关系,如下所述。当我尝试向课程添加新人员(即,将学生注册到课程)时,我在执行Linq语句的行中收到错误。我提供了代码的相关部分如下:

以下是抛出错误的代码:

Person userToRegister = _db.People.Single(p => p.Id == i.Value);//not null when debugging

int courseId = Convert.ToInt32(drp_Courses.SelectedValue);
Course myCourse = _db.Courses.Single(c => c.CourseId == courseId);//not null when debugging

myCourse.Members.Add(userToRegister);//This line throws the error
_db.SaveChanges();

这是Person类:

public class Person : IdentityUser
{
    [Required]
    [StringLength(50, ErrorMessage = "First name cannot be longer than 50 characters.")]
    public string FirstName { get; set; }

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

    public List<Course> RegisteredCourses { get; set; }
}

这是课程课程:

public class Course
{
    public int CourseId { get; set; }

    public string CourseTitle { get; set; }

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

以下是DbContext类中关系的定义:

 modelBuilder.Entity<Course>()
                    .HasMany(c => c.Members)
                    .WithMany(p => p.RegisteredCourses)
                    .Map(m => m.MapLeftKey("CourseId").MapRightKey("Id")
                                                      .ToTable("EnrollmentsToCourse"));

一切看起来都很完美。谁能告诉我这里缺少什么?

1 个答案:

答案 0 :(得分:4)

将该行更改为

Course myCourse = _db.Courses.Include(e => e.Members).Single(c => c.CourseId == courseId);

并检查

if (myCourse.Members == null)
{
    myCourse.Members = new List<Member>();
}