gpt4 book ai didi

entity-framework - Entity Framework 渴望加载单个实体

转载 作者:行者123 更新时间:2023-12-04 02:06:33 25 4
gpt4 key购买 nike

我的 WebApi Controller 的精简版是这样的:

[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 实体始终被填充,即使 includeEntities 参数为 false。

为什么它会急于只加载一个实体而不加载其他实体(按要求)?

截图如下:

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();
}
}

最佳答案

下面的Tip中基本上解释了Loading Related Data - Eager Loading EF Core 文档的一部分,但同样适用于 EF6 及以下版本:

Entity Framework Core will automatically fix-up navigation properties to any other entities that were previously loaded into the context instance. So even if you don't explicitly include the data for a navigation property, the property may still be populated if some or all of the related entities were previously loaded.

不幸的是,这种行为是不可控的,所以避免它的唯一选择是使用全新的 DbContext(或手动清理不需要的导航属性,但这很烦人且容易忘记).

关于entity-framework - Entity Framework 渴望加载单个实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42902155/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com