Frage zur bereichsbezogenen Lebensdauer von DbContext in Entity Framework Core
Posted: 18 Jan 2025, 19:37
Code: Select all
public class CommandObject
{
private readonly MyContext myContext;
public CommandObject(MyContext myContext)
{
this.myContext = myContext;
}
public void CreateFoo()
{
myContext.Foos.Add(new Foo());
myContext.SaveChanges();
}
}
public class SeparateFooService
{
private readonly CommandObject commandObject;
public SeparateFooService(CommandObject commandObject)
{
this.commandObject = commandObject;
}
public void CreateTwoFoos()
{
commandObject.CreateFoo();
commandObject.CreateFoo();
}
}
public class TransactionalFooService
{
private readonly MyContext myContext;
private readonly CommandObject commandObject;
public TransactionalFooService(MyContext myContext, CommandObject commandObject)
{
this.myContext = myContext;
this.commandObject = commandObject;
}
public void CreateTwoFoos()
{
using (var transaction = myContext.Database.BeginTransaction())
{
commandObject.CreateFoo();
commandObject.CreateFoo();
transaction.Commit();
}
}
}