2
votes

I'm creating a forum and I have recently implemented Simple Membership. What I'm trying to do now is display the actual name of who wrote the post. As of now I'm only able to display the UserId of the user.

I have two models: The Simplemembership model AccountModels, and my ForumModels. My Forummodel Posts contains a field for UserId.

I've tried adding some of the tables from AccountModels to my ForumModels, but this just caused an error (Since I was trying to create the same table twice)

I've tried creating a ViewModel that contained Posts and UserProfile, but couldn't populate it correctly with data.

Lastly I tried performing a join on the two tables Post and 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);

This created the error:

The specified LINQ expression contains references to queries that are associated with different contexts.

Any ideas on what I should do?

1
Are you using code first and add-migration to create your database in your ForumModels?Andy Brown
My ForumModels is databasefirst. The simple membership is codefirst.NoClueBlue

1 Answers

2
votes

It seems you're trying to perform a Join between two different contexts. You can either try to:

1) Make a call to the first context and persist the ID collection on a list like this:

var userIds = udb.UserProfiles.UserId.ToList();
var posts = from p in db.Posts 
    where p.TopicId == id && userIds.Contains(p.UserId) 
    select p;

2) Add the Posts to the same context as the one used by simple membership and you'll be able to use the join.

Update to Example code

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