efcore icon indicating copy to clipboard operation
efcore copied to clipboard

Mapping entity on left join

Open kvv842 opened this issue 6 years ago • 7 comments

Hello. Sory me bad English. I have two tables with relation one to many.

CREATE TABLE public."user"
(
  userid integer NOT NULL,
  surname character varying(50) NOT NULL,
  CONSTRAINT pk_auth_user PRIMARY KEY (userid)
)
CREATE TABLE public.userprofile
(
  userid integer NOT NULL,
  lang character varying(2),
  name character varying(50)
)

Data in tables

user
8;"s1"
9;"s2"

userprofile
8;"en";"Viktor"
8;"ru";"Виктор"

My code

namespace ConsoleAppEFV3
{
    class Program
    {
        static void Main(string[] args)
        {
            var eveDbContextConnectionString = $"Host=localhost;Port=5432;Database=testdb;Username=postgres;Password=postgres;CommandTimeout=300";

            var dbContextOptionsBuilder = new DbContextOptionsBuilder<MobileContext>(new DbContextOptions<MobileContext>());
            dbContextOptionsBuilder
                .UseNpgsql(eveDbContextConnectionString,
                options =>
                {
                    options.EnableRetryOnFailure(5, TimeSpan.FromSeconds(10), null);
                });

            using (var db = new MobileContext(dbContextOptionsBuilder.Options))
            {
                var l1 = db.Users
                            .Include(a => a.UserProfile)
                            .Where(a => a.Id == 8 || a.Id == 9)
                            .ToList();

                foreach (var u in l1)
                {
                    Console.WriteLine($"{u.Id} {u.Surname} {u.UserProfile?.LangId} {u.UserProfile?.Name}");
                }

            }

            Console.WriteLine("Hello World!");
        }
    }

    [Table("user", Schema = "public")]
    public class User
    {
        [Key]
        [Column("userid")]
        public int Id { get; set; }

        [Column("surname")]
        public string Surname { get; set; }

        public UserProfile UserProfile { get; set; }

        public User()
        {

        }
    }

    [Table("userprofile", Schema = "public")]
    public class UserProfile
    {
        [Column("userid")]
        public int Id { get; set; }

        [Column("lang")]
        public string LangId { get; set; }

        [Column("name")]
        public string Name { get; set; }
        public User User { get; set; }
    }

    public class MobileContext : DbContext
    {
        public MobileContext(DbContextOptions options) : base(options)
        { }

        public DbSet<User> Users { get; set; }
        public DbSet<UserProfile> UserProfiles { get; set; }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            builder.Entity<UserProfile>(ob =>
            {
                ob.HasOne(o => o.User)
                .WithOne(a => a.UserProfile)
                .HasForeignKey<UserProfile>(o => o.Id)
                .OnDelete(DeleteBehavior.Restrict);

                ob.HasKey(a => new { a.Id, a.LangId });
            });
        }
    }
}

EF generate valid SQL

SELECT a.userid, a.surname, "a.UserProfile".userid, "a.UserProfile".lang, "a.UserProfile".name
      FROM public."user" AS a
      LEFT JOIN public.userprofile AS "a.UserProfile" ON a.userid = "a.UserProfile".userid
      WHERE a.userid IN (8, 9)

I expect result image

I have result image

kvv842 avatar Feb 29 '20 09:02 kvv842

@kvv842 There are userprofile multiple rows with the same userid ID. How are those supposed to be handled in the model? (It looks like you're trying to setup a 1:1 relationship between user and userprofile, but that won't work if there are multiple profile rows with the same key value.)

ajcvickers avatar Mar 02 '20 20:03 ajcvickers

But profile lines have different keys. (UserProfile has key (a => new { a.Id, a.LangId }))

kvv842 avatar Mar 03 '20 07:03 kvv842

@kvv842 Is it intended that each User is associated with no more than one UserProfile? Or can a single User have multiple UserProfiles?

ajcvickers avatar Mar 03 '20 18:03 ajcvickers

I have to give a one-to-one relationship for a task within a single request. For example, a request comes to select several users with one profile. GET (user.id in (1,2,3) and profile.LangId = "ru") I am using a global filter for LangId. And it works well. But there is a request when it is necessary to process one to many.

kvv842 avatar Mar 04 '20 08:03 kvv842

@kvv842 EF can't configure the relationship as both one-to-one and one-to-many. It looks like what you have is a one-to-many relationship where in some scenarios the many is filtered down to a single entity. Is that correct?

ajcvickers avatar Mar 04 '20 17:03 ajcvickers

Yes, that's right. And most of these scenarios. So I'm trying to configure a one-to-one relationship. But I don’t understand why EF cannot build objects in this relation, because it builds the correct query for the SQL. Indeed, this is the key behavior of LEFT/INNER JOIN. And the result obtained is not correct.

kvv842 avatar Mar 05 '20 07:03 kvv842

@kvv842 EF doesn't support that. It must be modeled as one-to-many even if there is sometimes a filter that reduces that many to a single instance.

ajcvickers avatar Mar 09 '20 16:03 ajcvickers