我有一个循环将记录插入数据库(Firebird):
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, options))
{
taskList.Add(Task.Factory.StartNew(() =>
{
Parallel.ForEach(objectList, c =>
{
DoInsert(c, id);
});
}));
scope.Complete()
}
Run Code Online (Sandbox Code Playgroud)
如果插入失败,我希望能够批量回滚这些插入.但是,当我在Parallel.Foreach循环中执行插入时,事务范围不可见.我假设那是因为循环在不同的线程中运行.如果我使用TransactionScope作为串行插入执行此操作,一切正常.
我试图使用DependentTransaction但我似乎无法获取DoInsert函数的上下文.DoInsert只是打开一个连接并将C的内容写入数据库.
有任何想法吗?
谢谢,
所以.这可能是一个愚蠢的问题,但......
我只限于使用不支持EntityFramework的数据库,但我仍然希望将我的数据层分离到一个单独的程序集中.这意味着我需要共享域对象值,同时避免业务和数据层之间的循环引用.因此,我想知道构建一个持久性接口存储库是否可以接受,该存储库可以由业务层实现并相互独立地传递给数据层.
示例如下:
// Business Layer
public class Customer: IPersistableCustomer
{
private string name;
public string Name{ get { return this.name; } }
public void persist()
{
dataLayer.StoreCustomerInstance(this);
}
}
// DataLayer
public StoreCustomerInstance(IPersistableCustomer persistableCustomer)
{
// Do storage stuff
}
// Interface repository
public interface IPersistableCustomer
{
string Name { get; }
}
Run Code Online (Sandbox Code Playgroud)
我几乎可以肯定这是一个可怕的想法,但我不确定为什么.我有兴趣了解人们的想法,看看哪里有潜在的陷阱.