cheah ck
cheah ck

Reputation: 11

Entity Framework Core null relationship

I have created a simple EF Core to join two tables by using relationship (HasOne). But when I run it, the query only queries the master table (Employees) without joining to the second table (Contact) and it causes the model to not bind the data.

Could someone point out what I am missing in this code shown below? Thanks

public class Employees
{
    public int EmployeeId { get; set; }
    public string EmployeeName { get; set; }
    public Contact Contact { get; set; }
}

public class Contact
{
    public int Id { get; set; }
    public string ContactNumber { get; set; }
    public Employees Employee { get; set; }
    public int EmployeeId { get; set; }
}

internal class EmployeeMap : IEntityTypeConfiguration<Employees>
{
    public void Configure(EntityTypeBuilder<Employees> builder)
    {
        builder.HasKey(x => x.EmployeeId);
        builder.Property(p => p.EmployeeId).ValueGeneratedOnAdd();
        builder.HasOne(x => x.Contact).WithOne(y => y.Employee).HasForeignKey<Contact>(k => k.EmployeeId);
    }
}

public class ContactMap : IEntityTypeConfiguration<Contact>
{
    public void Configure(EntityTypeBuilder<Contact> builder)
    {
        builder.HasKey(x => x.Id);
        builder.Property(p => p.Id).ValueGeneratedOnAdd();
    }
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.ApplyConfigurationsFromAssembly(GetType().Assembly);
}

private EmployeeResponse GetEmployeeResponse()
{
    var emp = _context.Employees.FirstOrDefault();

    return new EmployeeResponse
        {
            ContactNumber = emp!.Contact.ContactNumber,
            EmployeeId = emp.EmployeeId,
        };
}

image

Upvotes: 0

Views: 219

Answers (1)

Dani
Dani

Reputation: 2036

Solutions:

1. Enable lazy loading:

DbContext.Configuration.LazyLoadingEnabled = true;

2. Or load it manually with .Include:

_context.Employees.Include(x => x.Contact).FirstOrDefault();

More information about navigation propertys in ef.

Upvotes: 1

Related Questions