Question

Hi I know this has been asked plenty of times, I'm not getting it through my skull

How to select Values from several tables

I made these two Linq queries

First

                r = (from d in db.stageManagers 
                 where d.profileID == UserID && d.verticalID == VerticalID 
                 select new StageModels()
                 {
                     UserId = d.profileID,
                     VerticalId = (int)d.verticalID,
                     VerticalStageID = d.stageID
                 }).FirstOrDefault();

Second

            r = (from d in db.stageManagerVerticals
                 where d.ID == r.VerticalId
                 select new StageModels()
                 {
                     VerticalName = d.verticalName
                 }
                 ).FirstOrDefault();

I want to make them one statement since they add data to one model and the tables they query have a Pk Fk relationship

In the first block d.verticalId is what I use to get the value(Name) in the secondblock, d.verticalId is primary key to stageManagerVerticals and foreign key in stageManager, How can i join these queries ?

I tried this:

    r = (from d in db.stageManagers  
          join c in db.stageManagerVerticals on d.stageID  equals c.ID
                 where d.profileID == UserID && d.verticalID == VerticalID 
                 select new StageModels()
                 {
                     UserId = d.profileID,
                     VerticalId = (int)d.verticalID,
                     VerticalStageID = d.stageID;
                     VerticalName = c.verticalName
                 }
            ).FirstOrDefault();
Was it helpful?

Solution

try with JOIN in LINQ to select values from more than one table

eg:

var innerJoinQuery =
    from category in categories
    join prod in products on category.ID equals prod.CategoryID
    select new { ProductName = prod.Name, Category = category.Name };

OTHER TIPS

var leftOuterJoin=(c in categories
                   join p in products on c.ID equals p.CategoryID into t
                   from temp in t.DefaultIfEmpty()
                   select new { ProductName = p.Name, Category = c.Name }
                  ).ToList();

You can utilize the Navigational Properties,

var r = db.stageManagers.Where(x => x.profileID == UserID && x.verticalID == VerticalID).
            Select(
                d => new StageModels() {
                            UserID = d.profileID, 
                            VerticalID = (int)d.verticalID, 
                            VerticalStageID = d.stageID, 
                            VerticalName = d.stageManagerVertical.verticalName
                            }
                ).FirstOrDefault();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top