在使用Entity Framework为主从表添加数据,当一个表添加数据成功,另一个表添加数据失败,这时候就需要用到事务回滚。
比如有以下关系的2张表。
客户端使用TransactionScope类可以实现事务回滚。
monospace; width: 100%; margin: 0em; background-color: #f0f0f0"> class Program
{static void Main(string[] args){try
{using (TransactionScope ts = new TransactionScope()){using (CountryDetailsEntities db = new CountryDetailsEntities()){Country country = new Country();
country.CountryName = "USA";
db.Countries.Add(country);db.SaveChanges();if (country.CountryID > 0)
{int a = 0;
int total = 10 / a;
State state = new State();
state.CountryID = country.CountryID;state.StateName = "NewYork";
db.States.Add(state);db.SaveChanges();}}ts.Complete();}}catch (Exception ex)
{throw;
}}}