Entity Framework Core - realtion between two tables without using primary key

.net .net-core c# entity-framework-core postgresql

Question

I would like to write Console application in dotnet core 2.1 with EFCore.Postgres 2.1.2.

I have two tables in existing Database. Every table has it's own Primary key, but these tables should be related via another field - UserId

db

My models:

public class UserAddress
{
    public int UserAddressId {get;set;}
    public int UserId {get;set;}
    public string City {get;set;}
    public string Street {get; set;}

    public virtual UserDetails UserDetails {get;set;}
}

public class UserDetails
{
    public int UserDetailId {get;set;}
    public int UserId {get;set;}

    public string Name {get;set;}
    public string Surname {get;set;}
}

How Can I 'Teach' Entityframework to join these tables wia UserId? I would like to use them like below

using (var MyDb = new GraffitiDbContext())
{
    var query = MyDb.UserAddress              
        .Include(row => row.UserDetails);

    foreach (var item in query)
    {
        Console.Writeline(item.UserDetails.Name);
    }
}
1
1
1/7/2019 11:58:46 AM

Popular Answer

With your current configuration you cannot infer this join as you would have to go from UserAddress to User to UserDetails. You can either add a relationship between UserAddress and UserDetails to make this traversal possible or you can use the following context navigation:

context.UserAddress.Include(x => x.User).ThenInclude(x => x.UserDetails)

The problem is that the User can have many UserDetails thus when you include the User on the UserAddress query, there is a possibility that you would get many records.

Address1 -> User1 -> UserDetail1
Address1 -> User1 -> UserDetail2
0
1/7/2019 1:31:43 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow