Search code examples
c#.net-coreentity-framework-corepomelo-entityframeworkcore-mysqlef-core-5.0

Entity framework produces left join when condition on foreign key


I have 2 models:

public class User
{
    public int Id { get; set; }

    [Required] 
    [MaxLength(50)]
    public string Email { get; set; }

    [Required] 
    [MaxLength(100)] 
    public string Password { get; set; }
}

and

public class Questionnaire
{
    public int Id { get; set; }

    [Required] 
    [MaxLength(500)] 
    public string Title { get; set; }

    public User User { get; set; }
}

I would like to use this query to retrieve all questionnaires of certain user:

List<Questionnaire> questionnaires = this._dbContext.Questionnaires.Where(a => a.User.Id == 1).ToList();

It works, but entity framework produces this sql query:

SELECT `q`.`Id`, `q`.`Title`, `q`.`UserId`
FROM `Questionnaires` AS `q`
     LEFT JOIN `Users` AS `u` ON `q`.`UserId` = `u`.`Id`
WHERE `u`.`Id` = 1;

In my opinion, left join is unnecessary. Please is there any workaround to avoid this left join? Thank you in advance.


Solution

  • You will need to expose UserId property on Questionnaire manually:

    public class Questionnaire
    {
        public int Id { get; set; }
    
        [Required] 
        [MaxLength(500)] 
        public string Title { get; set; }
    
        public int UserId { get; set; }
        public User User { get; set; }
    }
    

    And use it in query instead of a.User.Id:

    var questionnaires = this._dbContext.Questionnaires
        .Where(a => a.UserId == 1) // use UserId instead of User.Id
        .ToList();