asp.net-mvc - MVC 使用 SimpleMembership 检索用户名

标签 asp.net-mvc entity-framework ef-code-first simplemembership ef-database-first

我正在创建一个论坛,并且最近实现了简单成员(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/

相关文章:

asp.net-mvc - 调试 ASP.NET MVC 绑定(bind)的最佳实践

c# - 在 Entity Framework 中分离和附加对象时出错

c# - 首先使用代码查找带有 Entity Framework 时间戳的更新条目

entity-framework - 防止 Entity Framework 在每个类型继承的表中添加重复的键

azure - 使用远程连接字符串在 Azure 上执行代码优先迁移

c# - Automapper - 多对象源和一个目标

c# - 在我的 Windows 服务应用程序中自行托管 MVC 2 应用程序的最佳方式是什么?

.net - 使用 Entity Framework 和 System.Data.SQLite 的级联删除问题

c# - 带有存储过程的代码优先 Entity Framework 从复杂的全文搜索返回结果

entity-framework - Entity Framework 代码首先使用 Guid 作为身份与另一个身份列