不能使用’System.Data.Entity.Core.Objects.ObjectQuery类型的实例调用
我想通过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 Discussion_CreateDate { get; set; } public string Discussion_CreateBy { get; set; } public string Comment_User { get; set; } public IEnumerable Comments { get; set; } } public class CommentVM { public int Comment_ID { get; set; } public Nullable 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); }
获得以下错误
1[Project.Models.AspNetUser]' cannot be called with instance of type 'System.Data.Entity.Core.Objects.ObjectQuery
在类型’System.Data.Entity.DbSet1[Project.Models.AspNetUser]' cannot be called with instance of type 'System.Data.Entity.Core.Objects.ObjectQuery
上声明的方法’Project.Models.AspNetUser Find(System.Object [])’1[Project.Models.AspNetUser]' cannot be called with instance of type 'System.Data.Entity.Core.Objects.ObjectQuery
1 [Project.Models.AspNetUser]’
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
而不是实际的注释集合
解决它的最简单方法是将所有注释带入内存(因为你无论如何都需要它们):
上述就是C#学习教程:不能使用’System.Data.Entity.Core.Objects.ObjectQuery类型的实例调用分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
var comments = db.AB_DiscussionComments.Where(c => c.Discussion_ID == Discussion_ID).ToList();
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/953010.html