使用 Entity Framework Core,我正在批量保存要保存的对象。在此批处理过程中,我想显式创建一个新对象,但不希望创建其他对象。
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
对象的情况下保存某些内容
?
我考虑过使用 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();
}
关于c# - 如果已经有正在跟踪的已更改对象,是否有任何方法可以使用 Entity Framework Core 保存单个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49877078/