我对实体框架有疑问。在我的程序中,我首先用数据填充了我的DbContext。然后,我需要从数据库表中删除所有数据,但前提是要保存新数据。如果db.Savechanges()抛出异常,我需要我的旧数据仍然在表中。
我的代码是:
static void Main(string[] args)
{
PdmContext db = new PdmContext();
FillDbContext();
try
{
if (db.SaveChanges() > 0)
{
using (var del = new PdmContext())
{
DeleteModel.deleteFromAllTables();
}
db.SaveChanges();
}
}
catch (Exception exp)
{
Logger.Log("Exception (global catch));
}
}
我似乎无法弄清楚。有人可以帮忙吗? :)
答案 0 :(得分:2)
您可以使用select g.groupname, m.membername, su.*
from (select groupid, memberid, max(subscribed) as subscribed, max(sdate) as sdate, max(unsubscribed) as unsubscribed, max(udate) as udate
from ((select groupid, memberid, 1 as subscribed, date as sdate, 0 as unsubscribed, null as udate
from subscribed s
) union all
(select groupid, memberid, 0 as subscribed, null as sdate, 1 as unsubscribed, date as udate
from subscribed s
)
) su
group by groupid, memberid
) join
groups g
on g.groupid = su.groupid join
member m
on m.memberid = su.memberid;
,如果在某个阶段操作失败,它将确保恢复在其范围内完成的操作:
Transaction
现在,对数据库的更改将是原子性的,因此它将仅保留所有更改或根本不保留所有更改。为了简单起见,我没有包括异常处理代码,但是由于任何原因,如果未执行using (var scope = new TransactionScope(TransactionScopeOption.Required))
{
using (var del = new PdmContext())
{
DeleteModel.deleteFromAllTables();
}
db.SaveChanges();
scope.Complete(); // commits the transaction
}
并且控件存在事务块而未执行,则该事务将被回滚。
答案 1 :(得分:0)
您需要使用交易。
查看如何使用它:
using (var dbContextTransaction = PdmContext.Database.BeginTransaction())
{
try
{
// HERE your operation insert etc.
PdmContext.SaveChanges();
dbContextTransaction.Commit(); // here, apply your operation
}
catch (Exception)
{
dbContextTransaction.Rollback(); // here, undo your operations
}
}
答案 2 :(得分:0)
您可以通过事务管理来处理这种情况。
有两种处理方法。
1)您可以对所有操作使用单个dbcontext,而不是对单个操作创建多个dbcontext。
using (var context = new SchoolContext())
{
try
{
context.Students.Add(new Student()
{
FirstName = "Rama2",
StandardId = standard.StandardId
});
context.Courses.Add(new Course() { CourseName = "Computer Science" });
context.SaveChanges();
transaction.Commit();
}
catch (Exception ex)
{
transaction.Rollback();
Console.WriteLine("Error occurred.");
}
}
2)使用单个DbContextTransaction对象:
using (var context = new SchoolContext())
{
context.Database.Log = Console.Write;
using (DbContextTransaction transaction = context.Database.BeginTransaction())
{
try
{
context.Students.Add(new Student()
{
FirstName = "Rama2",
StandardId = standard.StandardId
});
context.SaveChanges();
context.Courses.Add(new Course() { CourseName = "Computer Science" });
context.SaveChanges();
transaction.Commit();
}
catch (Exception ex)
{
transaction.Rollback();
Console.WriteLine("Error occurred.");
}
}
}
我希望它对您有用。