如果已经有正在跟踪的已更改对象,是否有任何方法可以使用 Entity Framework Core 保存单个对象?

Is there any way to save a single object using Entity Framework Core if there are already altered objects it is tracking?

使用 Entity Framework 核心,我正在对要保存的对象进行批处理。在此批处理过程中,我想显式创建一个新对象,但我不想创建其他对象。

public void Generate()
{
    DbContext context = GetDbContext();
    context.Add(new MyUser());
    context.Add(new MyUser());
    DoSomethingElse(context);
    context.SaveChanges();
}

public void DoSomethingElse(DbContext context)
{
    var something = new Something();
    // add new object and save only this new object
}

有什么方法可以在不保存两个 User 对象的情况下保存 something 吗?

我考虑过使用 DbContext 的新实例,实例化的成本会很高吗?

如果 DoSomethingElse 不依赖于之前的操作,则考虑将其分成不同的工作单元。

例如

public void Generate() {
    DbContext context = GetDbContext();
    DoSomething(context);
    DoSomethingElse(context);
}

public void DoSomething(DbContext context) {
    var something = new Something();

    // add new object and save only this new object

    context.SaveChanges();
}

public void DoSomethingElse(DbContext context) {
    context.Add(new MyUser());
    context.Add(new MyUser());    
    context.SaveChanges();
}