ef core one-to-one property is always null

.net-core ef-core-2.0 entity-framework-core

Question

I'm trying to define (using data annotations, that's the project pattern, not using the fluent api) a one-to-one relationship but the navigation property (public virtual HolidayType HolidayType) is always null. The db table is creating the ForeignKey correctly using the annotation [ForeignKey("HolidayTypeId")].

Holiday Model

[Table("Holidays", Schema = "PTO")]
public class Holiday : EntityBase
{
    ...
    public long HolidayTypeId { get; set; }
    [ForeignKey("HolidayTypeId")]
    public virtual HolidayType HolidayType { get; set; }
    ...
}

db FK constraint

ALTER TABLE [PTO].[Holidays]  WITH CHECK ADD  CONSTRAINT  [FK_Holidays_HolidayTypes_HolidayTypeId] FOREIGN KEY([HolidayTypeId])
 REFERENCES [PTO].[HolidayTypes] ([Id])
ON DELETE CASCADE
GO

Holiday Types Table

[Table("HolidayTypes", Schema = "PTO")]
public class HolidayType : EntityBase
{
    [Required]
    [MaxLength(200)]
    public string Description { get; set; }
    public bool IsActive { get; set; }
}

EntityBase

public class EntityBase
{
    [Key]
    public long Id { get; set; }
    [Required]
    [MaxLength(200)]
    public string Name { get; set; }
    public Guid CreatedByGuidId { get; set; }
    public DateTime DateCreated { get; set; }
    public Guid UpdatedByGuidId { get; set; }
    public DateTime? DateUpdated { get; set; }
    [Timestamp]
    public byte[] RowVersion { get; set; }
}

Here's the repository call, the holidays are retrieved but they are missing the HolidayType property - always null. My understanding, using the ForeignKey annotation, the query does not need to have an .include statement. My understanding is obviously flawed so my next step is to try the include statement to verify. I'm hoping that an include statement doesn't require an addition db call if that is the answer to my issue.

    public async Task<IEnumerable<T>> ListAsync(Expression<Func<T, bool>> predicate)
    {
        return await ApplicationDbContext.Set<T>().Where(predicate).ToListAsync();
    }
1
0
1/25/2018 4:28:30 PM

Popular Answer

Looks like the .Include statement is needed but it breaks my repository implementation so I need to rethink that.

This now hydrates the HolidayType:

    public async Task<List<Holiday>> GetHolidaysByEmployerId(long employerId, int? year = null)
    {
        Expression<Func<Holiday, bool>> predicate = holiday => holiday.EmployerId == employerId;
        var result = await ApplicationDbContext.Set<Holiday>().Where(predicate)
                            .Include(holiday => holiday.HolidayType)
                            .ToListAsync();
        return result.ToList();
    }
0
1/25/2018 4:46:45 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