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
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);
}
}
UserAddress
orUserDetails
with the sameUserId
? Can there be noUserAddress
forUserDetails
with a speificUserId
and vice versa? – ImantasUserId
is not unique in one of the tables. Also don't you haveUser
table whereUserId
is a PK, so these 2 tables relate indirectly through it? – Ivan StoevUserId
in both entities as alternate key and try to map the one-to-one relationship withmodelBuilder.Entity<UserAddress>().HasOne(e => e.UserDetails).WithOne().HasPrincipalKey<UserAddress>(e => e.UserId).HasForeignKey<UserDetails>(e => e.UserId)
. It might eventually work, but I personally would keepUser
entity (even with just PK property) and the real relationships. – Ivan Stoev