我有两张桌子,HOTEL 和 OWNER。两者都有 Identity 列,但其中一个具有另一个表所需的外键。
我需要同时以事务方式添加两条记录,但如果在主表上插入失败,我需要回滚为辅助表写入记录的事务。
据我了解,我需要 .SaveChanges() 从辅助表中获取自动生成的 ID,但这似乎也正在提交事务。
有没有其他方法可以做到这一点?
public class HOTEL
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Int64 HOTEL_ID { get; set; }
public string blah1 { get; set; }
public string blah2 { get; set; }
}
public class OWNER
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Int64 OWNER_ID { get; set; }
public string blah3 { get; set; }
public string blah4 { get; set; }
public Int64 HOTEL_ID { get; set; }
[ForeignKey("HOTEL_ID")]
public virtual HOTEL HOTEL { get; set; }
}
...
public class MyContext : DbContext
{
public MyContext() : base() { }
public MyContext(string connectionString) : base(connectionString) { }
public DbSet<HOTEL> HOTELs { get; set; }
public DbSet<OWNER> OWNERs { get; set; }
public ObjectContext ObjectContext
{
get
{
return (this as IObjectContextAdapter).ObjectContext;
}
}
}
...
Int64 ret = 0;
// Suppress required for DB2.
using (var transaction = new TransactionScope(TransactionScopeOption.Suppress))
{
try
{
using (var context = new MyContext())
{
var secondaryEntity = new HOTEL();
context.HOTELs.Add(secondaryEntity);
// This appears to commit the changes in the trasaction.
context.SaveChanges();
primaryEntity.HOTEL_ID = secondaryEntity.HOTEL_ID;
context.OWNERs.Attach(primaryEntity);
context.Entry(primaryEntity).State = primaryEntity.OWNER_ID == 0 ? EntityState.Added : EntityState.Modified;
context.SaveChanges();
ret = primaryEntity.OWNER_ID;
}
}
catch (Exception ex)
{
// Deal with errors.
}
if (ret != 0)
{
transaction.Complete();
}
}
return ret;