尝试添加/编辑applicationUser的相关数据属性,以便可以为用户记录注释
ApplicationUser.cs
public class ApplicationUser : IdentityUser
{
public virtual ICollection<UserNote> UserNotes { get; set; }
[Required]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required]
[Display(Name = "Last Name")]
public string LastName { get; set; }
}
UserNote.cs
public class UserNote
{
[Key]
public int UserNoteId { get; set; }
public string Message { get; set; }
public string ApplicationUserID { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
}
控制器
[HttpPost, ActionName("Edit")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> EditPost(string id, ApplicationUser applicationUser)
{
if (ModelState.IsValid)
{
var userFromDb = _db.ApplicationUser
.Include(n => n.UserNotes)
.Include(r => r.UserRoles)
.AsNoTracking().FirstOrDefault(m => m.Id == id);
UserNote note = _db.UserNote.Single(x => x.UserNoteId == 1);
userFromDb.LastName = applicationUser.LastName;
userFromDb.FirstName = applicationUser.FirstName;
//Error accessing related data properties
userFromDb.UserNotes.Message = applicationUser.UserNotes.Message;
await _db.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(applicationUser);
}
我收到的'ICollection'不包含'Message'的定义,并且没有可访问的扩展方法'Message'接受类型为'ICollection'的第一个参数
答案 0 :(得分:0)
UserNotes
是一个集合,因此您需要在获取其Message
属性之前访问某个索引。
// Use .Count to check if the list contains any number.
if(applicationUser.UserNotes.Count != 0){
// .FirstOrDefault() will return the first object in that list, if there is none, it would return null.
userFromDb.UserNotes.FirstOrDefault().Message = applicationUser.UserNotes.FirstOrDefault().Message;
}else{
// this is just to let you know if it's empty just in case if you don't debug
return Content("Your collection is empty.");
}
如果您要查找特定记录,也可以在列表中使用.IndexOf()或.Where()。
如果您要添加新笔记或正在编辑现有笔记,那么我对所尝试内容的了解还不是很清楚。如果这对您不起作用,请在评论中让我进一步知道。
答案 1 :(得分:0)
尝试如下编辑applicationUser的相关数据属性:
build