将项添加到实体的集合属性中
本文关键字:集合 属性 实体 添加 | 更新日期: 2023-09-27 18:07:03
我正在Visual Studio Ultimate 2013中的MVC 5项目上工作。
我需要处理一个学生ApplicationUser
在注册到系统后应该加入学习小组的情况,如果他填写了一个注册码(仅用于加入学习小组),他已经提供了。
问题是,当我试图添加一个项目到StudyGroup
属性ICollection<ApplicationUser> Members
我得到
系统。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; }
}
最后是我的Model Builder for StudyGroup:
modelBuilder.Entity<StudyGroup>()
.HasMany(s => s.Members)
.WithMany(m => m.StudyGroup);
将这些项目添加到实体属性的正确方法应该是什么,为什么我的方法不起作用,请问?很多谢谢!
看起来你没有在你的用户上初始化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; }
}