简体   繁体   English

尽管配置了查询过滤器,但已加载 EF Core 导航属性

[英]EF Core Navigation Property is loaded although Query Filter is configured

I use EF Core 5.0.4 with a MS SQL Server and Lazy Loading.我将 EF Core 5.0.4 与 MS SQL 服务器和延迟加载一起使用。 My entities all derive from BaseEntity which contains a Deleted property.我的实体都派生自包含Deleted属性的BaseEntity For all entities I configured a global query filter which allows to load only entities where Deleted is set to false .对于所有实体,我配置了一个全局查询过滤器,它只允许加载Deleted设置为false的实体。 Now I've got a Project entity and an Appointment entity and an:m entity ProjectAppointment .现在我有一个Project实体和一个Appointment实体和一个:m 实体ProjectAppointment

public class ProjectAppointment : BaseEntity
{
    public ProjectAppointment(Guid? id, Project project, Appointment appointment) : base(id)
    {
        Project = project;
        Appointment = appointment;
    }

    public ProjectAppointment(Guid? id, Guid projectId, Guid appointmentId) : base(id)
    {
        ProjectId = projectId;
        AppointmentId = appointmentId;
    }

    public ProjectAppointment()
    {
    }

    public Guid ProjectId { get; private set; }
    public virtual Project Project { get; private set; }
    public Guid AppointmentId { get; private set; }
    public virtual Appointment Appointment { get; private set; }
}

All three types derive from BaseEntity .所有三种类型都派生自BaseEntity If I load an appointment from database which contains a projectAppointment with was recently changed to Deleted = true , this navigation property will still be returned by ef core although the query filter should avoid this:如果我从包含最近更改为Deleted = true的 projectAppointment 的数据库中加载约会,则 ef core 仍将返回此导航属性,尽管查询过滤器应避免这种情况:

在此处输入图像描述

I created a simplified repository to demonstrate the issue.我创建了一个简化的存储库来演示这个问题。 It also occurs without lazy loading.它也发生在没有延迟加载的情况下。

How can I configure entity framework to not lazy load navigation properties with Deleted = true ?如何将实体框架配置为不使用Deleted = true延迟加载导航属性?

Well, I have checked your sample.好吧,我已经检查了你的样品。

You have loaded record, updated and trying to check that this records is not appears in other collection.您已加载记录、更新并尝试检查此记录是否未出现在其他集合中。 Problem here that ChangeTracker already knows about this records and knows to which collection it should be applied even it is not returned from database.这里的问题是ChangeTracker已经知道这些记录并且知道它应该应用到哪个集合,即使它没有从数据库返回。

Workarounds:解决方法:

  •  _appContext.Entry(pa).State = EntityState.Detached;
  •  _appContext.ChangeTracker.Clear();
  • Update in one DbContext , load in another.在一个DbContext中更新,在另一个中加载。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM