我正在尝试在另一个<AppUser>
对象中包含Project
个对象的集合。
我的模特:
public class Project
{
public int ProjectID { get; set; }
[Required(ErrorMessage = " Please enter a project name")]
public string Name { get; set; }
[Required(ErrorMessage = " Please enter a project description")]
public string Description { get; set; }
//HERE'S MY COLLECTION OF <APPUSER> OBJECTS
public virtual ICollection<AppUser> ProjectManagers { get; set; }
}
在我看来,我要求与<AppUser>
关联的电子邮件添加到此列表中。这是与此视图关联的ViewModel:
public class AddProjectManagerViewModel
{
[Required]
[EmailAddress(ErrorMessage = "Please ensure email is valid")]
[UIHint("email")]
public string Email { get; set; }
public int ProjectID { get; set; }
}
视图:
@model AddProjectManagerViewModel
@{
ViewBag.Title = "Add PM";
Layout = "_Layout";
}
<div class="col-xs-12 buffer">
<div class="text-center">
<h3>Enter the new Project Manager's email:</h3>
</div>
<div><span asp-validation-for="Email" class="text-danger"></span></div>
<form asp-action="AddProjectManager">
<div class="form-group">
<label asp-for="Email"></label>
<input asp-for="Email" class="form-control" />
</div>
<div class="text-center">
<button class="btn btn-primary" asp-route-projectId="@Model.ProjectID" type="submit">Add to PMs</button>
</div>
</form>
</div>
在我的控制器中,我有POST方法。问题是,List<AppUser>
不是持久性的,每次调用该操作方法时都会显示null
:
[HttpPost]
[Authorize]
public async Task<IActionResult> AddProjectManager(int projectId, string email)
{
var pmToAdd = await userManager.FindByEmailAsync(email);
if (pmToAdd != null)
{
var proj = repository.Projects.FirstOrDefault(p => p.ProjectID == projectId);
if(proj != null)
{
//HERE proj.ProjectManagers IS ALWAYS NULL EVEN IF THIS METHOD HAS BEEN PREVIOUSLY CALLED SUCCESSFULLY
if(proj.ProjectManagers == null) { proj.ProjectManagers = new List<AppUser>(); }
proj.ProjectManagers.Add(pmToAdd);
TempData["message"] = $"{pmToAdd.Email} added to {proj.Name} Project Managers";
return View("Edit", proj );
}
TempData["message"] = $"Error finding project in database.";
return View();
}
TempData["message"] = $"User not found. Ensure that email is linked to a registered user";
return View();
}
我应该如何设置这种方法以使模型的public virtual ICollection<AppUser> ProjectManagers { get; set; }
持久化?
EDIT 这是我的存储库方法:
public void AddProjectManager(int projectID, AppUser user)
{
Project proj = context.Projects.FirstOrDefault(p => p.ProjectID == projectID);
if(proj != null)
{
proj.ProjectManagers.Add(user);
context.SaveChanges();
}
}
我也已将action方法中的proj.ProjectManagers.Add(pmToAdd);
更改为repository.AddProjectManager(projectId, pmToAdd);
,但每次调用时List<AppUser>' is still
为空