Search code examples
c#entity-framework-corerelation

EF Core Relationship Not bringing back related records


I am using .NET Entity Framework 8.0.1

I have 3 classes - Attraction, Address and Advert There is a 1 to many relationship between Attraction and Advert and a 1 to 1 relationship between Attraction and Address And I have created the Db using migrations.

Here are my classes:

public class Attraction : BaseEntity
{
    [Required]
    [MaxLength(100)]
    public string Name { get; set; }

    [Required]
    [MaxLength(100)]
    public string Website { get; set; }

    public Address Address { get; set; }

    public ICollection<Advert> Adverts { get; } = new List<Advert>();

    public Attraction()
    {
    }

}

public class Address : BaseEntity
{
    [Required]
    public Guid AttractionId { get; set; }

    [Required]
    [MaxLength(100)]
    public string Line1 { get; set; }

    [Required]
    [MaxLength(100)]
    public string Line2 { get; set; }

    [Required]
    [MaxLength(100)]
    public string Line3 { get; set; }

    [Required]
    [MaxLength(100)]
    public string Line4 { get; set; }

    [Required]
    [MaxLength(100)]
    public string Line5 { get; set; }

    [Required]
    [MaxLength(16)]
    public string PostCode { get; set; }

    public Address()
    {
    }
}

public class Advert : BaseEntity
{
    [Required]
    public Guid AttractionId { get; set; }

    [Required]
    public string Description { get; set; }

    [Required]
    public DateTime DisplayFrom { get; set; }

    [Required]
    public DateTime DisplayTo { get; set; }

    [Required]
    public int DisplayType { get; set; }

    [Required]
    public string PanelColour { get; set; }

    public Advert()
    {
    }

}

The base Entity class which they derive from :

public class BaseEntity
{

    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Required]
    public Guid Id { get; set; }

}

And in the Application DBContext class i have set up the relationships like this:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{          
    modelBuilder.Entity<Attraction>()
        .HasMany(e => e.Adverts)
        .WithOne()
        .HasForeignKey(e => e.AttractionId);

    modelBuilder.Entity<Attraction>()
        .HasOne(e => e.Address)
        .WithOne()
        .HasForeignKey<Address>(e => e.AttractionId);
}

When I run the select select query to retrieve the Attraction class, the Address is always null and the Adverts list is always empty.

And this is my query

public async Task<List<Attraction>> SelectAll()
{
    return await Task.Run(() => AppDbContext.Attractions.ToList());
}

Solution

  • When you are not using Lazy-Loading, you have to include related entities in your query.

    You can do this with the .Include(x => x.Adverts).ThenInclude(x => x.Address) method to include both navigations.