Search code examples
asp.netentity-frameworklinq

Join 3 tables in SQL using Entity Framework and LINQ


Trying to join 3 SQL tables with EF and LINQ, not sure how to write the right script. I know how to do it with 2 tables, but got a bit lost once a third table came into play.

I have 3 tables, the models look like that:

User:

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

UserName:

public class UserName
{
    public int Id { get; set; }
    public int UserId { get; set; }
    public string Name { get; set; } = null!;
    public User User { get; set; } = null!;
}

UserNameValues:

public class UserNameValues 
{
    public int Id { get; set; }
    public int UserNameId { get; set; }
    public string Value { get; set; } = null!;
 
    public UserName UserName { get; set; } = null!;
}

I want to get the value from UserNameValues

where user.id = x and username.name = x

I appreciate any help!


Solution

  • Try this (assuming a variable called context with a collection of UserNameValues):

    context.UserNameValues.Where(unv => unv.UserName.Name == "juan" && unv.UserName.User.Id == x);
    

    I personally dislike the SQL-like syntax and stopped using it a long time ago in favor of the method calls, precisely because it's confusing.