Handling relationships in EF Core 3.1.2 & FirebirdClient 7.5.0

c# entity-framework entity-framework-core firebird foreign-keys

Question

I am not quite sure how to handle a relationship in entity framework core using the firebird provider. I got a table 'Users' and 'Employees'. They got a One-To-One relationship using the column 'username'. I tried several tutorials but could not get it to work. My goal is to access the field 'Employee' by calling user.Employee But in the most cases it's just empty or gives errors when using LazyLoad. It think I dont get the right approach on this.

Btw I already asked in the firebird.net provider google group

User.cs:

public class User {        
    public string Username { get; set; } // Primary key in db
    public string Passwd { get; set; }
    /* ... */
    public virtual Employee Employee { get; set; }
}

Employee.cs:

 public class Employee {          
        public int Id { get; set; }
        public int EmployeeNumber { get; set; }
        /* ... */
        [ForeignKey("User")]
        public string Username { get; set; } // Foreign key in db
        public virtual User User { get; set; }        
    }

Context.cs

    protected override void OnModelCreating(ModelBuilder modelBuilder) {
        configureTable(modelBuilder.Entity<Employee>());
        configureTable(modelBuilder.Entity<User>());
        /* ... */
    }

    private static void configureTable(EntityTypeBuilder<Employee> tc) {
        tc.HasKey(x => new { x.Id });

        tc.Property(x => x.Id).HasColumnName("EMPLOYEE_ID");
        tc.Property(x => x.Username).HasColumnName("USERNAME");
        /* ... */
        //tc.HasOne(x => x.User).WithOne(u => u.Employee).HasForeignKey<User>(n => n.Username); // Is this the correct configuration?
        tc.ToTable("EMPLOYEES");
    }

    private static void configureTable(EntityTypeBuilder<User> tc) {
        tc.HasKey(x => new { x.Username });
        /* ... */
        tc.Property(x => x.Username).HasColumnName("USERNAME");
        tc.Property(x => x.Passwd).HasColumnName("PASSWD");

        //tc.HasOne(x => x.Employee).WithOne(u => u.User).HasForeignKey<Employee>(n => n.Username); // Do I have to do something similar here?

        tc.ToTable("USERS");
    }
1
0
3/16/2020 10:26:14 AM

Popular Answer

Thanks to Jiří Činčura from the firebird.net provider Google Group I found the solution myself. I just forgot to include the related entities when querying. So instead of:

return await db.Users.SingleAsync(a => a.Username == username);

I just had to do:

return await db.Users
       .Include(user => user.Employee)
       .SingleAsync(a => a.Username == username);
0
3/17/2020 2:34:58 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