我有以下实体:
public class Animal
{
public int Id { get; set; }
public string Name { get; set; }
/// <summary>
/// Current Animal Status
/// </summary>
public virtual AnimalStatus CurrentAnimalStatus
{
get { return AnimalStatuses.OrderByDescending(x => x.VersionNo).First(); }
}
/// <summary>
/// List of all Animal Statuses
/// </summary>
public virtual ICollection<AnimalStatus> AnimalStatuses { get; set; }
/// <summary>
/// List of all Animal Operations
/// </summary>
public virtual ICollection<AnimalOperation> AnimalOperations { get; set; }
}
和
public class AnimalStatus
{
public int Id { get; set; }
public int VersionNo { get; set; }
public int BloodCount { get; set; }
public int AnimalId { get; set; }
public virtual Animal Animal { get; set; }
}
我只对最新的AnimalStatus
感兴趣,因此想使用View来填充CurrentAnimalStatus
属性,而无需使用ICollection<AnimalStatus>
。 Animal
实体的其余部分应由EF核心填充。
当前AnimalStatus
表可容纳300,000条记录,因此将EF Core与...一起使用非常慢
_dbContext.Animal.Include(x => x.AnimalStatus);
是否可以在EF Core中从SQL视图填充实体上的导航属性?
CREATE VIEW [dbo].[CurrentAnimalStatusView]
AS
WITH ANIMAL_EVENTS_CTE AS
(
SELECT
AnimalId,
BloodCount,
ROW_NUMBER() OVER (PARTITION BY AnimalId ORDER BY VersionNo DESC) AS RowNumber --RowNumber = 1 indicates the latest status
FROM
AnimalBloodTests
)
SELECT
AnimalId,
BloodCount
FROM
ANIMAL_EVENTS_CTE cte
WHERE
RowNumber = 1 --Only interested in latest status for each AnimalId
答案 0 :(得分:0)
您可以为视图创建模型并将其映射到Dbset。
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<CurrentAnimalStatus>(eb =>
{
eb.HasNoKey();
eb.ToView("CurrentAnimalStatusView");
});
base.OnModelCreating(modelBuilder);
}