c# – 实体框架6:尽管延迟加载被关闭,但相关实体自动添加到父实体

我有2个类,SalesSubCategory和SalesCategory:

[Table("SALES.SubCategory")]
public class SalesSubCategory
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }

    public int CategoryID { get; set; }

    public string Name { get; set; }

    [ForeignKey("CategoryID")]
    public SalesCategory SalesCategory { get; set; }
}

[Table("SALES.Category")]
public class SalesCategory
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }

    public string Name { get; set; }
}

此方法返回SalesSubCategories List而不加载SalesCategory对象

public class TestController : Controller
{
    private readonly MD_Context _context;

    public TestController(MD_Context context)
    {
        _context = context;
    }
    public async Task<List<SalesSubCategory>> NoRelated()
    {
        var subCategories = await _context.SalesSubCategories.ToListAsync();
        return subCategories;
    } 

Related Entity not Loaded

此方法返回SalesSubCategories列表,并加载SalesCategory对象

public async Task<List<SalesSubCategory>> Related() 
{
    var subCategories = await _context.SalesSubCategories.ToListAsync();
    var categories = await _context.SalesCategories.ToListAsync();
    return subCategories;
} 

Related Entity loaded

MD_Context配置为禁用延迟加载:

Configuration.LazyLoadingEnabled = false;

这是预期的行为吗?我的首选结果是不预先加载SalesCategory对象实体.

谢谢.

最佳答案
是的,这是预期的行为.

当从上下文加载实体时,游戏中的实体会被附加以便跟踪对它们的任何修改,也就是说,由于先前的加载而得到结果.

您可以通过请求查询以非跟踪方式执行来解决此问题.这不会使entityframework将它与您的新查询相关联.

var subCategories = await _context.SalesSubCategories.ToListAsync();
var categories = await _context.SalesCategories.AsNoTracking().ToListAsync();

转载注明原文:c# – 实体框架6:尽管延迟加载被关闭,但相关实体自动添加到父实体 - 代码日志