我正在创建一个论坛,我最近实施了简单会员资格。我现在要做的是显示谁撰写帖子的实际名称。截至目前,我只能显示用户的UserId。
我有两个模型:Simplemembership模型AccountModels和我的ForumModels。 我的Forummodel帖子包含UserId的字段。
我已经尝试将一些表从AccountModels添加到我的ForumModels,但这只是导致错误(因为我试图创建相同的表两次)
我尝试创建一个包含Posts和UserProfile的ViewModel,但无法正确填充数据。
最后,我尝试在两个表Post和Userprofile
上执行连接 var posts = (from p in db.Posts
join u in udb.UserProfiles
on p.UserId equals u.UserId
where p.TopicId == id
select p);
return View(posts);
这造成了错误:
指定的LINQ表达式包含对与不同上下文关联的查询的引用。
关于我应该做什么的任何想法?
答案 0 :(得分:2)
您似乎正在尝试在两个不同的上下文之间执行连接。您可以尝试:
1)调用第一个上下文并将ID集合保存在如下列表中:
var userIds = udb.UserProfiles.UserId.ToList();
var posts = from p in db.Posts
where p.TopicId == id && userIds.Contains(p.UserId)
select p;
2)将帖子添加到与简单会员使用的相同的上下文中,您就可以使用联接。
更新为示例代码
//This will retrieve the posts from the database.
//ToList() will translate and execute the SQL statement,
//so you can manipulate the colleciton in memory
var posts = (from p in db.Posts
where p.TopicId == id
select p).ToList();
//Get all the user IDs on the post collection.
var userIds = posts.Select(p => p.UserId).Distinct();
//Then we will select the users in the posts
var users = ubd.UserProfiles.Where(u => userIds.Contains(u.UserId)).ToList();
//Now you have both collections in memory and you can perform the join
var joined = from p in posts
join u in users
on p.UserId equals u.UserId
select new {Title = p.Title, UserName = u.UserName};