我有简单的论坛应用程序,每个主题都有很多帖子,每个帖子可能会被多个用户所喜欢。应用程序实体模型如下:
public class ForumTopic
{
public int ForumTopicId { get; set; }
public string Subject { get; set; }
public string UserId { get; set; }
public virtual User User { get; set; }
public virtual ICollection<ForumPost> ForumPosts { get; set; }
}
public class ForumPost
{
public int ForumPostId { get; set; }
public string Message { get; set; }
public int ForumTopicId { get; set; }
public virtual ForumTopic ForumTopic { get; set; }
public string UserId { get; set; }
public virtual User User { get; set; }
public virtual ICollection<ForumPostFavorite> ForumPostFavorites { get; set; }
}
public class ForumPostFavorite
{
public string UserId { get; set; }
public User User { get; set; }
public int ForumPostId { get; set; }
public ForumPost ForumPost { get; set; }
}
我想把当前用户最喜欢的帖子看作如下。但是此查询抛出“由于对象的当前状态而导致操作无效”异常。我确信这个查询无一例外地在实体框架6中运行,但在Entity Framework核心中会发生这种异常。
public IActionResult Favorite()
{
var userId = _userManager.GetUserId(User);
var list = _dbContext.ForumPostFavorites
.Where(e => e.UserId == userId)
.Select(e => e.ForumPost)
.Take(10)
.Select(e => new ForumPostFavoriteVm
{
ForumPostId = e.ForumPostId,
ForumTopicId = e.ForumTopicId,
Message = e.Message,
Subject = e.ForumTopic.Subject,
}).ToList();
return View(list);
}
当我从查询中删除此行“Subject = e.ForumTopic.Subject”时,查询将无任何例外地运行。
答案 0 :(得分:0)
尝试将Skip()&amp;投影后拿():
var list = _dbContext.ForumPostFavorites
.Where(e => e.UserId == userId)
.Select(e => e.ForumPost)
.Select(e => new ForumPostFavoriteVm
{
ForumPostId = e.ForumPostId,
ForumTopicId = e.ForumTopicId,
Message = e.Message,
Subject = e.ForumTopic.Subject,
})
.Take(10)
.ToList();