我正在创建一个论坛,并且最近实现了简单成员(member)资格。我现在想做的是显示帖子作者的真实姓名。截至目前,我只能显示用户的 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);
这造成了错误:
The specified LINQ expression contains references to queries that are associated with different contexts.
关于我应该做什么有什么想法吗?
最佳答案
您似乎正在尝试在两个不同的上下文之间执行连接。您可以尝试:
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};
关于asp.net-mvc - MVC 使用 SimpleMembership 检索用户名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16748316/