当事务类型为 Table时,LINQ to SQL 事务
我正在尝试创建一个事务来包装多个 LINQ to SQL SubmitChanges() 调用。
代码
System.Data.Common.DbTransaction trans = null;
using (DbContext context = new DbContext())
{
context.Connection.Open()
trans = context.Connection.BeginTransaction();
context.Transaction = trans; // <-- ERROR HERE: Cannot be done!
.... // Several calls to delete objects with context.SaveChanges()
trans.Commit();
}
问题
在我们的数据库模式(它早于我,并且与应用程序紧密相关)中,我们有一个名为 Transaction
的表。
这意味着上面代码中的 Transaction 属性实际上不是 IDbTransaction 类型,并且我无法将 trans 对象分配给 context.Transaction。 context.Transaction
实际上是 Table
类型。
问题
鉴于我有一个名为 Transaction 的表,这一事实当前不可更改,如何将事务分配给我的上下文?
尽管我熟悉 LINQ to SQL,但这是我第一次在多个调用周围使用事务,因此我也准备好接受这样的事实:我一开始可能没有以正确的方式执行此操作,并且冲突的表名甚至可能不是问题......
I'm attempting to create a transaction to wrap around several LINQ to SQL SubmitChanges() calls.
Code
System.Data.Common.DbTransaction trans = null;
using (DbContext context = new DbContext())
{
context.Connection.Open()
trans = context.Connection.BeginTransaction();
context.Transaction = trans; // <-- ERROR HERE: Cannot be done!
.... // Several calls to delete objects with context.SaveChanges()
trans.Commit();
}
Problem
In our database schema (which pre-dates me, and is heavily tied into the application), we have a table called Transaction
.
This means that the Transaction property in the code above is not actually an IDbTransaction type, and I am unable to assign the trans object to context.Transaction. context.Transaction
is actually of type Table<Transaction>
.
Question
How can I assign a transaction to my context, given the currently unchangeable fact that I have a table named Transaction?
Although I'm familiar with LINQ to SQL, this is the first time for me using a Transaction around multiple calls, so I'm also ready to accept that I may not be doing this the right way in the first place, and that the conflicting table name may not even be an issue...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果
DataContext
中的Transaction
属性被您的DbContext
类隐藏,只需转换:这样
Transaction
就可以解析由编译器转换为DataContext.Transaction
而不是DbContext.Transaction
。或者,您可以使用单独的变量,如果您要进行多次此类调用,这可能会很有用:(
我不知道这是否是使用事务的正确方法 - 这只是绕过您的方法命名冲突。)
If the
Transaction
property fromDataContext
is being hidden by yourDbContext
class, just cast:That way
Transaction
is resolved by the compiler toDataContext.Transaction
instead ofDbContext.Transaction
.Alternatively you could use a separate variable, which could be useful if you have several such calls to make:
(I have no idea whether or not this is the right way to use the transaction by the way - it's just the way to get around your naming collision.)