实体框架急于加载单个实体

时间:2017-03-20 11:14:39

标签: entity-framework

我的WebApi控制器的删节版本是这样的:

[HttpGet, Route("")]
public async Task<IHttpActionResult> Search(bool includeEntities)
{
    IQueryable<VersionTopic> results = DbContext.VersionTopics;
    if (includeEntities)
    {
        results = results.Include(o => o.CreatedBy);
        results = results.Include(o => o.LastSavedBy);
        results = results.Include(o => o.Topic.LastSavedBy);
        results = results.Include(o => o.Topic.CreatedBy);
        results = results.Include(o => o.Topic.PACKType.LastSavedBy);
        // etc...
    }

    results = results.OrderBy(o => o.SortOrder);

    return Ok(result.ToList());
}

出于某种原因,即使LastSavedBy参数为false,也始终填充includeEntities实体。

为什么它只是急于加载这一个实体而不是其他实体(如果需要)?

以下是截图:

enter image description here

我的模型定义如下:

public class VersionTopic
{
    [Key]
    [Required]
    public Guid VersionTopicId { get; set; }

    [Required]
    [Index("IX_VersionTopic_VersionId_TopicId", IsUnique = true, Order = 0)]
    public Guid VersionId { get; set; }

    [Required]
    [Index("IX_VersionTopic_VersionId_TopicId", IsUnique = true, Order = 1)]
    public Guid TopicId { get; set; }

    [Required(AllowEmptyStrings = true)]
    [MaxLength(250)]
    public string Name { get; set; }

    public string KeyMessage { get; set; }

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

    [Required]
    public Guid CreatedById { get; set; }

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

    [Required]
    public Guid LastSavedById { get; set; }

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

    public virtual ICollection<VersionRecommendation> VersionRecommendations { get; set; } = new List<VersionRecommendation>();

    [ForeignKey("CreatedById")]
    public virtual ApplicationUser CreatedBy { get; set; }

    [ForeignKey("LastSavedById")]
    public virtual ApplicationUser LastSavedBy { get; set; }

    [ForeignKey("TopicId")]
    public virtual Topic Topic { get; set; }

    [ForeignKey("VersionId")]
    public virtual Version Version { get; set; }

    public VersionTopic()
    {
        VersionTopicId = Guid.NewGuid();
    }
}

1 个答案:

答案 0 :(得分:3)

它基本上在EF Core文档的Loading Related Data - Eager Loading部分的提示中进行了解释,但这同样适用于EF6及以下版本:

  

Entity Framework Core会自动将导航属性修复到先前加载到上下文实例中的任何其他实体。因此,即使您没有明确包含导航属性的数据,如果之前加载了部分或全部相关实体,该属性仍可能会被填充。

不幸的是,这种行为是不可控制的,因此唯一可以避免使用的选项是使用全新的DbContext(或者手动清理不需要的导航属性,但这很烦人且容易忘)。