我想通过userId
查找用户名此代码段工作
Discussion_CreateBy = db.AspNetUsers.Find(discussion.CreatedBy).UserName,
这一次不适用于以下控制器类
Comment_CreateBy = db.AspNetUsers.Find(c.CreatedBy).UserName,
这是我的模型类
public class DiscussionVM
{
public int Disussion_ID { get; set; }
public string Discussion_Title { get; set; }
public string Discussion_Description { get; set; }
public Nullable<System.DateTime> Discussion_CreateDate { get; set; }
public string Discussion_CreateBy { get; set; }
public string Comment_User { get; set; }
public IEnumerable<CommentVM> Comments { get; set; }
}
public class CommentVM
{
public int Comment_ID { get; set; }
public Nullable<System.DateTime> Comment_CreateDate { get; set; }
public string Comment_CreateBy { get; set; }
public string Comment_Description { get; set; }
}
这是整个控制器类
public ActionResult Discussion_Preview()
{
int Discussion_ID = 1;
var discussion = db.AB_Discussion.Where(d => d.Discussion_ID == Discussion_ID).FirstOrDefault();
var comments = db.AB_DiscussionComments.Where(c => c.Discussion_ID == Discussion_ID);
DiscussionVM model = new DiscussionVM()
{
Disussion_ID = discussion.Discussion_ID,
Discussion_Title = discussion.Discussion_Name,
Discussion_Description = discussion.Discussion_Name,
Discussion_CreateBy = db.AspNetUsers.Find(discussion.CreatedBy).UserName,
Discussion_CreateDate = discussion.CreatedDate,
Comments = comments.Select(c => new CommentVM()
{
Comment_ID = c.Comment_ID,
Comment_Description = c.Comment_Discription,
Comment_CreateBy = db.AspNetUsers.Find(c.CreatedBy).UserName,
Comment_CreateDate = c.CreatedDate
})
};
return View(model);
}
获得以下错误
方法&#39; Project.Models.AspNetUser Find(System.Object [])&#39;声明类型&#39; System.Data.Entity.DbSet
1[Project.Models.AspNetUser]' cannot be called with instance of type 'System.Data.Entity.Core.Objects.ObjectQuery
1 [Project.Models.AspNetUser]&#39;
答案 0 :(得分:1)
Discussion_CreateBy = db.AspNetUsers.Find(discussion.CreatedBy).UserName
可行,因为讨论是一个内存中对象,因为您通过调用FirstOrDefault
来执行查询:
var discussion = db.AB_Discussion.Where(d => d.Discussion_ID == Discussion_ID).FirstOrDefault();
另一方面,在以下声明中:
db.AspNetUsers.Find(c.CreatedBy).UserName
c
尚未查询,因为
db.AB_DiscussionComments.Where(c => c.Discussion_ID == Discussion_ID)
返回IQueriable
而不是实际的评论集合
解决问题的最简单方法是将所有评论都记录在内存中(因为无论如何都需要它们):
var comments = db.AB_DiscussionComments.Where(c => c.Discussion_ID == Discussion_ID).ToList();