Skip to content

EF Core Inheritance: Profile Field Null on Retrieval Despite of Configured Relationships #32352

Open

Description

I'm encountering an issue with Entity Framework Core (EF Core) related to lazy loading, inheritance, and property retrieval. Initially, I had the following entity classes:

public class Pool
{
    public int Id { get; set; }
    public Profile? Profile
    {
        get
        {
            return ORMAProfileAccessor as Profile ?? ORMBProfileAccessor;
        }

        set
        {
            switch (value)
            {
                case AProfile aProfile:
                    ORMAProfileAccessor = aProfile;
                    break;
                case BProfile bProfile:
                    ORMBProfileAccessor = bProfile;
                    break;
                default:
                    throw new InvalidCastException("Invalid profile type");
            }
        }
    }
    internal virtual AProfile? ORMAProfileAccessor { get; set; }
    internal virtual BProfile? ORMBProfileAccessor { get; set; }
}

public abstract class Profile
{
    public Profile() { }
    public int Id { get; set; }
}

public class AProfile : Profile
{
    public AProfile() { }
    public virtual Pool? Pool { get; set; }
}

public class BProfile : Profile
{
    public BProfile() { }
    public virtual Pool? Pool { get; set; }
}

In the OnModelCreating method, I configured the relationships as follows:

modelBuilder.Entity<AProfile>().HasOne(P => P.Pool).WithOne(Q => Q.ORMAProfileAccessor).HasForeignKey<Pool>("AProfileId").IsRequired(false);
modelBuilder.Entity<BProfile>().HasOne(P => P.Pool).WithOne(Q => Q.ORMBProfileAccessor).HasForeignKey<Pool>("BProfileId").IsRequired(false);
modelBuilder.Entity<Pool>().Ignore(P => P.Profile);

The issue I'm facing now is that after saving a Pool object to the database with associated Profile, upon retrieving the Pool elsewhere in the code, the Profile field remains null. However, retrieving a Profile separately shows that the Pool field within the Profile object is correctly populated. For example:

var retrievedPool = dbContext.Pools.FirstOrDefault();
if (retrievedPool != null)
{
    Console.WriteLine($"Retrieved Pool ID: {retrievedPool.Id}");
    Console.WriteLine($"Retrieved Pool Profile ID: {retrievedPool.Profile?.Id}"); // This returns null
}

How can I ensure that when retrieving a Pool, the Profile field is populated with the associated Profile type?

Any insights or suggestions would be highly appreciated. Thank you!

EF Core version: 6.0.16
Database provider:Microsoft.EntityFrameworkCore.SqlServer
Target framework: .NET 6.0
IDE: Visual Studio 2022 17.4

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions