简体   繁体   中英

Join Identity Table and Data Table MVC5 EF6

My data table is a list of articles written by authenticated users.

On the index page I would like to show a list of articles as well as the DisplayName of the author for each. The problem is the DisplayName is stored in my applicationDBContext identity table and my Data is stored in a DBContext (seperate databases on my server). The unique USERID key is on both tables, iD on the Identity table and Author ID on the Data table. I have tried different tihngs, giving different errors, the most common one being

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

The code that generates that error is as follows:

var arts = (from a in db.Articles
                        join uid in iDdb.Users
                            on a.AuthorID equals uid.Id
                        select new ArticleVM
                   {
                       ID = a.ID,
                       ArticleTitle = a.ArticleTitle,
                       ArticleBody = a.ArticleBody.Substring(0, 200),
                       ArticleCategory = a.ArticleCategory,
                       DateCreated = a.DateCreated,
                       AuthorID = uid.DisplayName
                   }).AsEnumerable();

db.Articles in the Data tableon the data database and IDdb.Users is the User table (on the identity database). I can write an SQL query to generate what I need, but how do I put that data into a ViewModel, example, this SQL query will give me what I need:

var query = @"select artDB.*, usrDB.DisplayName from Article as artDB inner
                            join [IGTSIAppUsersTest1].dbo.AspNetUsers as usrDB on 
                            artDB.AuthorID = usrDB.Id order by artDB.ID Desc";
            var arts = db.Database.ExecuteSqlCommand(query);

Can anyone suggest a way to do this that is still somewhat efficient? I found one way to make it work but it requires a ridiculous amount of code and really hurts performance.

I found a way to do this. It works as long as you are only viewing data and not changing data. I found the answer here

    string query = (@"select a.*, usr.DisplayName as 'DisplayName' from article a
join identitytablename.dbo.AspNetUsers usr on
datatable.Id = a.authorid");
            IEnumerable<ArticleIndexVM> results = db.Database.SqlQuery<IndexViewModel>(query);

Works well as long as your ViemModel Types and names match up with the results of the query table names and types

One of the approach here, you can use the same context for Users and Articles. As following link below.

Use the same database for both my custom entities and identity context?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM