我正在尝试定义(使用数据注释,即项目模式,不使用流畅的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; }
...
}
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; }
}
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();
}
答案 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();
}