ef核心一对一属性始终为null

时间:2018-01-25 16:28:31

标签: .net-core entity-framework-core ef-core-2.0

我正在尝试定义(使用数据注释,即项目模式,不使用流畅的api)一对一的关系,但导航属性(public virtual HolidayType HolidayType)始终为null。 db表正在使用注释[ForeignKey("HolidayTypeId")]正确创建ForeignKey。

假日模特

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

db FK约束

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

假日类型表

[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; }
}

这是存储库调用,检索假期但它们缺少HolidayType属性 - 始终为null。我的理解是,使用ForeignKey注释,查询不需要.include语句。我的理解显然是有缺陷的,所以我的下一步是尝试使用include语句进行验证。我希望include语句不需要添加db调用,如果这是我的问题的答案。

    public async Task<IEnumerable<T>> ListAsync(Expression<Func<T, bool>> predicate)
    {
        return await ApplicationDbContext.Set<T>().Where(predicate).ToListAsync();
    }

1 个答案:

答案 0 :(得分:0)

看起来需要.Include语句,但它会破坏我的存储库实现,所以我需要重新考虑它。

这现在保留了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();
    }