【问题标题】:MVC Retrieving username with SimpleMembershipMVC 使用 SimpleMembership 检索用户名
【发布时间】:2013-05-25 09:46:58
【问题描述】:

我正在创建一个论坛,并且我最近实施了简单会员。我现在要做的是显示写这篇文章的人的实际姓名。截至目前,我只能显示用户的 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 表达式包含对与不同上下文关联的查询的引用。

对我应该做什么有什么想法吗?

【问题讨论】:

  • 您是否使用代码优先和添加迁移在您的 ForumModels 中创建数据库?
  • 我的 ForumModels 是数据库优先的。简单的成员资格是 codefirst。

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


【解决方案1】:

您似乎正在尝试在两个不同的上下文之间执行联接。您可以尝试:

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};

【讨论】:

  • 感谢您的回复。在 1 的第一行中,我得到 Does not contain a definition for UserId 我的 udb 是 private UsersContext udb = new UsersContext(); 2)我是 MVC 新手,不完全了解上下文是什么以及如何向其中添加“帖子”。
  • 您的问题不完全在于 MVC,而在于实体框架。您正在使用 SimpleMembership,它使用“代码优先”方法,在该方法中,您将实体定义为类,并将它们转换为 SQL 表。这里的问题是这些表是在两种不同的上下文中定义的(一种用于简单的成员资格,另一种用于您的数据存储)。我会用一些可以让你得到名字的东西来更新答案。
  • 我试过你的新代码。我必须添加属性“p.Title”但我从视图中得到了这个错误。 The model item passed into the dictionary is of type 'System.Linq.Enumerable+<JoinIterator>d__614[Forum3.Models.Posts,Forum3.Models.UserProfile,System.Int32,f__AnonymousType42[System.String,System.String]]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[Forum3.Models.Posts]'.` 不知道我应该使用什么作为模型视图
  • 我添加了“title”作为示例。我不知道你的桌子的结构。我正在生产的是一个匿名对象。为了将您的对象绑定到视图,您必须创建一个新类 ViewModel,它将具有您需要在屏幕上显示的组合属性。您的视图引发错误,因为它期望 IEnumerable 作为模型,但您正在传递匿名对象...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-10
  • 2011-10-23
相关资源
最近更新 更多