将项添加到实体的集合属性

时间:2014-06-05 23:39:40

标签: c# asp.net entity-framework asp.net-mvc-5

我正在开发Visual Studio Ultimate 2013中的MVC 5项目。

我需要处理一个情况,即ApplicationUser学生在注册到系统后应该加入一个研究组,如果他填写注册码(仅用于加入研究组)他已经提供。

问题在于,当我尝试将项目添加到StudyGroup属性ICollection<ApplicationUser> Members时,我得到了

  

System.NullReferenceException:未将对象引用设置为对象的实例。

注册操作:

public async Task<ActionResult> Register(RegisterViewModel model)
    {
        UserManager.UserValidator = new UserValidator<ApplicationUser>(UserManager) { AllowOnlyAlphanumericUserNames = false };

        if (ModelState.IsValid)
        {
            var user = new ApplicationUser()
            { 
                UserName = model.UserName,
                Name = model.Name,
                Surname = model.Surname
            };

            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                await SignInAsync(user, isPersistent: false);
                UserManager.AddToRole(user.Id, "Student");

                var group =
                    (from g in db.StudyGroups
                     where g.RegistrationCode == model.GroupCode
                     select g).FirstOrDefault();

                if (group != null)
                {
                    user.StudyGroup.Add(group);
                    group.Members.Add(user);
                }

                return RedirectToAction("Index", "Home");
            }
            else
            {
                AddErrors(result);
            }
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

ApplicationUser:

public class ApplicationUser : IdentityUser
{
    public string Name { get; set; }
    public string Surname { get; set; }
    public virtual ICollection<StudyGroup> StudyGroup { get; set; }
    public virtual ICollection<Test> Tests { get; set; }
}

StudyGroup:

public class StudyGroup
{
    [Key]
    public int StudyGroupId { get; set; }

    [Required(ErrorMessage = "Group Name is required.")]
    [Display(Name = "Group Name")]
    public string Name { get; set; }

    [Display(Name = "Registration Code", Description = "The code which students will use to join this study group.")]
    public string RegistrationCode { get; set; }

    public virtual ICollection<ApplicationUser> Members { get; set; }

    public virtual ICollection<Template> Templates { get; set; }
}

最后我的模型构建器用于StudyGroup:

modelBuilder.Entity<StudyGroup>()
            .HasMany(s => s.Members)
            .WithMany(m => m.StudyGroup);

将这些项目添加到实体属性的正确方法应该是什么,为什么不是我的工作方法呢?非常感谢!

1 个答案:

答案 0 :(得分:0)

您好像没有初始化用户的ICollection<StudyGroup> StudyGroup属性?

尝试添加初始化属性的默认构造函数:

public class ApplicationUser : IdentityUser
{
    public ApplicationUser() 
    {
        this.StudyGroup = new List<StudyGroup>();
        this.Tests = new List<Test>();
    }
    public string Name { get; set; }
    public string Surname { get; set; }
    public virtual ICollection<StudyGroup> StudyGroup { get; set; }
    public virtual ICollection<Test> Tests { get; set; }
}