[2 days left] What’s wrong with your cloud strategy? Learn why multicloud solutions matter with Nimble Storage.Register Now

x
?
SolvedPrivate

LINQ To Entity - Easy Left Join

Posted on 2013-10-24
4
Medium Priority
?
93 Views
Last Modified: 2016-02-10
Hi Experts!

Thanks for reading this.

Trying to convert this T-SQL to Linq to Entity:
SELECT 
  sq.SurveyQuestionText
, sac.SurveyScaleText
FROM [dbo].SurveyQuestions sq
LEFT JOIN 
			(
			SELECT 
			 sa.SurveyQuestionID
			, sc.SurveyScaleText
			FROM SurveyUserAnswers sa
			INNER JOIN SurveyScales as sc
				ON sa.SurveyScaleID = sc.SurveyScaleID
			WHERE sa.UserID = 2
			) As sac
			ON sq.SurveyQuestionID = sac.SurveyQuestionID
WHERE sq.SurveyQuestionCounter <= 10 

Open in new window

This is the INNER JOIN:
SomeDB db = new SomeDB();
var UserAnswered = (from ua in db.SurveyUserAnswers
                    join s in db.SurveyScales on ua.SurveyScaleID equals s.SurveyScaleID
                    where ua.UserID == 2
                    select new 
                    { 
                        ua.SurveyQuestionID,
                        s.SurveyScaleText
                    }).ToList();

Open in new window

A LEFT JOIN looks like this:
var query = (from sq in SurveyQuestions
            from sac in  //UserAnswered above
                             .Where(x => sq.SurveyQuestionID == x.SurveyQuestionID)
                             .DefaultIfEmpty()
            select new
			{sq.SurveyQuestionText
             ,sac.SurveyScaleText}).ToList();

Open in new window


Stuck trying to put the two pieces together.

The query would return All questions and if the user has answered the question it would be null for UserAnswered.

Any ideas? TIA!

If you need more info... This will create the class:
public class SurveyUserAnswer
{
    [Key, Required]
    public int SurveyUserAnswerID { get; set; }
    [Required]
    public int SurveyScaleID { get; set; }
    [Required]
    public int SurveyQuestionID { get; set; }
    [Required]
    public int UserID { get; set; }
    public DateTime DateCreated { get; set; }

    public virtual SurveyScale SurveyScale { get; set; }
    public virtual SurveyQuestion SurveyQuestion { get; set; }
    public virtual User User { get; set; }

    public SurveyUserAnswer()
    {
        DateCreated = DateTime.UtcNow;
    }
}


public class SurveyQuestion
{
    [Key, Required]
    public int SurveyQuestionID { get; set; }
    [Required]
    public int SurveyQuestionCounter { get; set; }
    [Required, MaxLength(500)]
    public string SurveyQuestionText { get; set; }
    public DateTime DateCreated { get; set; }

    public virtual ICollection<SurveyUserAnswer> SurveyUserAnswer { get; set; }

    public SurveyQuestion()
    {
        DateCreated = DateTime.UtcNow;
    }
}

public class SurveyScale
{
    [Key, Required]
    public int SurveyScaleID { get; set; }
    [Required]
    public int SurveyScaleValue { get; set; }
    [Required, MaxLength(8)]
    public string SurveyScaleText { get; set; }
    public DateTime DateCreated { get; set; }

    public virtual ICollection<SurveyUserAnswer> SurveyUserAnswer { get; set; }

    public SurveyScale()
    {
        DateCreated = DateTime.UtcNow;
    }
}

Open in new window

This will create the dummy data content:
        var SurveyScales = new List<SurveyScale> 
        {
        new SurveyScale {SurveyScaleValue = 0, SurveyScaleText = "Never"},
        new SurveyScale {SurveyScaleValue = 1, SurveyScaleText = "Seldom"},
        new SurveyScale {SurveyScaleValue = 2, SurveyScaleText = "Sometime"},
        new SurveyScale {SurveyScaleValue = 3, SurveyScaleText = "Always"}
        };
        SurveyScales.ForEach(r => db.SurveyScales.Add(r));
        db.SaveChanges();

        var SurveyQuestions = new List<SurveyQuestion>
        {
            new SurveyQuestion {SurveyQuestionCounter = 1, SurveyQuestionText = "Question A"},
            new SurveyQuestion {SurveyQuestionCounter = 2, SurveyQuestionText = "Question B"},
            new SurveyQuestion {SurveyQuestionCounter = 3, SurveyQuestionText = "Question C"},
            new SurveyQuestion {SurveyQuestionCounter = 4, SurveyQuestionText = "Question D"}
        };
        SurveyQuestions.ForEach(r => db.SurveyQuestions.Add(r));
        db.SaveChanges();

        var SurveyUserAnswers = new List<SurveyUserAnswer>
        {
            new SurveyUserAnswer {SurveyScaleID = 1,  SurveyQuestionID = 1,  UserID = 1},
            new SurveyUserAnswer {SurveyScaleID = 2,  SurveyQuestionID = 2,  UserID = 1},
            new SurveyUserAnswer {SurveyScaleID = 3,  SurveyQuestionID = 3,  UserID = 1},
            new SurveyUserAnswer {SurveyScaleID = 4,  SurveyQuestionID = 4,  UserID = 1},

            new SurveyUserAnswer {SurveyScaleID = 1,  SurveyQuestionID = 1,  UserID = 2},
            new SurveyUserAnswer {SurveyScaleID = 2,  SurveyQuestionID = 2,  UserID = 2}          
        };
        SurveyUserAnswers.ForEach(r => db.SurveyUserAnswers.Add(r));
        db.SaveChanges();

Open in new window

0
Comment
Question by:allanau20
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
4 Comments
 
LVL 96

Accepted Solution

by:
Bob Learned earned 2000 total points
ID: 39599231
You should be able to combine those two queries, if you take advantage of LINQ's laziness.  That means that you need to stay away from things that execute, like ToList.

Example:

var UserAnswered = (from ua in db.SurveyUserAnswers
                    join s in db.SurveyScales on ua.SurveyScaleID equals s.SurveyScaleID
                    where ua.UserID == 2
                    select new 
                    { 
                        ua.SurveyQuestionID,
                        s.SurveyScaleText
                    });

var query = (from sq in SurveyQuestions
            join sac in UserAnswered
                  on sq.SurveyQuestionID equals sac.SurveyQuestionID into leftJoin
            from result in leftJoin.DefaultIfEmpty()
            select new
			{sq.SurveyQuestionText,
                         sac.SurveyScaleText}).ToList();

Open in new window

0
 
LVL 5

Author Comment

by:allanau20
ID: 39599239
Thanks TheLearnedOne; I will try it sometime later today ...
0
 
LVL 5

Author Comment

by:allanau20
ID: 39599879
took your solution and extended it:
var UserAnswered = (from ua in db.SurveyUserAnswers
                    join s in db.SurveyScales on ua.SurveyScaleID equals s.SurveyScaleID
                    where ua.UserID == 2
                    select new
                    {
                        ua.SurveyQuestionID,
                        s.SurveyScaleText,
                        s.SurveyScaleValue
                    });

var query = (from sq in db.SurveyQuestions
                join sac in UserAnswered
                    on sq.SurveyQuestionID equals sac.SurveyQuestionID into leftJoin
                from result in leftJoin.DefaultIfEmpty()
                where sq.SurveyQuestionCounter <= 10 
                select new
                {
                    sq.SurveyQuestionText,  
                    SurveyScaleText = result.SurveyScaleText != null ? result.SurveyScaleText : null,
                    SurveyScaleValue = result.SurveyScaleValue != null ? result.SurveyScaleValue : (int?)null        
                });

Open in new window

0
 
LVL 5

Author Closing Comment

by:allanau20
ID: 39599881
Thanks for your help!!
0

Featured Post

Veeam Task Manager for Hyper-V

Task Manager for Hyper-V provides critical information that allows you to monitor Hyper-V performance by displaying real-time views of CPU and memory at the individual VM-level, so you can quickly identify which VMs are using host resources.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article describes how to use the timestamp of existing data in a database to allow Tableau to calculate the prior work day instead of relying on case statements or if statements to calculate the days of the week.
This post looks at MongoDB and MySQL, and covers high-level MongoDB strengths, weaknesses, features, and uses from the perspective of an SQL user.
This course is ideal for IT System Administrators working with VMware vSphere and its associated products in their company infrastructure. This course teaches you how to install and maintain this virtualization technology to store data, prevent vuln…
Are you ready to place your question in front of subject-matter experts for more timely responses? With the release of Priority Question, Premium Members, Team Accounts and Qualified Experts can now identify the emergent level of their issue, signal…

649 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question