无法访问applicationUser的外键数据,“ ICollection”不包含“消息”的定义

尝试添加/编辑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'的第一个参数

wuyangsunyu 回答:无法访问applicationUser的外键数据,“ ICollection”不包含“消息”的定义

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()

如果您要添加新笔记或正在编辑现有笔记,那么我对所尝试内容的了解还不是很清楚。如果这对您不起作用,请在评论中让我进一步知道。

,

尝试如下编辑applicationUser的相关数据属性:

build
本文链接:https://www.f2er.com/3120599.html

大家都在问