如何知道一个对象是否被 Entity Framework Core 跟踪

How to know if an object is tracked by Entity Framework Core

我在 ASP.NET Core Web API 项目中使用 .NET 6 和 Entity Framework Core 6 (6.0.2)。

假设我有:

public class MyModel 
{
    public Guid Id { get; set; }
    public string MyData { get; set; }
    //etc...
}

public class ApplicationDbContext : DbContext
{
    public DbSet<MyModel> MyModels { get; set; }

    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> opt) : base(opt)
    {
    }
}

如果我在一个带有对象 MyModel myModel 的通用函数中,那么我如何知道 MyModel 的这个实例是否是由 Entity Framework Core 跟踪的实体?

我正在寻找类似这样的函数:

ApplicationDbContext context = ...
MyModel myModel = ...
//ecc...
bool result = context.IsOneOfMyEntity(myModel);

可以使用Entry方法

This method may be called on an entity that is not tracked. You can then set the State property on the returned entry to have the context begin tracking the entity in the specified state.

并检查 State property for value other than Detached

Detached 0 The entity is not being tracked by the context.

例如

bool tracked = context.Entry(myModel).State != EntityState.Detached;