Home > Enterprise >  Join 3 tables in SQL using Entity Framework and LINQ
Join 3 tables in SQL using Entity Framework and LINQ

Time:11-05

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!

CodePudding user response:

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.

CodePudding user response:

Refer to below link. I got stuck on how to write LINQ for joining three different tables as follows:

https://social.msdn.microsoft.com/Forums/en-US/21444ee2-0f39-4f6b-9b6b-50977e629136/join-three-tables-using-linq-query?forum=aspadoentitylinq

  • Related