我一直在关注Massive ORM。不要忘记,只是看,我还没有做任何编码。
我对保存数据事务的可能性感兴趣。我已经看到在一次交易中可以在同一张表中保存20行。但是当我想在单个交易中保存订单及其订单行时会发生什么?这可能吗,怎么样?
答案 0 :(得分:6)
Massive的Save()方法声明如下所示:
Save(params object[] things)
...并且在内部它对传入的每个对象执行foreach循环,并在单个事务中将其保存到数据库中,因此它已经完成了您希望它执行的操作。
现在,如果你想自己控制交易,那就让我们开始吧。
首先,Massive中的几乎所有方法都标记为虚拟,因此我们可以覆盖派生类中的任何方法,这样我们就可以做到。现在所有对Save()的调用最终都会通过一个Execute()方法,该方法接受一个IEnumerable的DbCommand,所以我们将在派生类中重写该方法。
这是我们的派生类:
public class ExtendedDynamicModel : DynamicModel
{
// Lets add two properties that we will reference in our overridden Execute method
public System.Data.IDbConnection Connection;
public System.Data.IDbTransaction Transaction;
public ExtendedDynamicModel( string connectionStringName, string tableName = "",
string primaryKeyField = "", string descriptorField = "" )
: base( connectionStringName, tableName, primaryKeyField, descriptorField )
{
}
// Lets override the Execute method and if we've supplied a Connection, then let's
// using our own custom implementation otherwise use Massive's default implementation.
public override int Execute( IEnumerable<System.Data.Common.DbCommand> commands )
{
if ( Connection == null ) return base.Execute( commands );
var result = 0;
foreach ( var cmd in commands as IEnumerable<System.Data.IDbCommand> )
{
cmd.Connection = Connection;
cmd.Transaction = Transaction;
result += cmd.ExecuteNonQuery();
}
return result;
}
}
所以现在我们只需要为我们的新ExtendedDynamicModel类提供我们自己的IDbConnection和IDbTransaction,如下所示:
var database = new ExtendedDynamicModel( "YourConnectionString" );
using ( var connection = database.Connection = database.OpenConnection() )
{
using ( var tx = database.Transaction = connection.BeginTransaction() )
{
// Do your saving here
if ( true )
{
tx.Commit();
}
else
{
tx.Rollback();
}
}
}
现在,如果需要,我们可以完全控制提交或回滚事务。
链接到Massive的源代码以供参考:https://github.com/robconery/massive/
答案 1 :(得分:1)
我一直在关注这个问题,这是我使用大规模默认交易的看法:我正在利用
table.Execute(IEnumerable<DbCommands>)
这里有一些假设的示例代码
private bool BigSave(int id)
{
var saveList = new List<DbCommand>();
var tblO = new Order();
var order = tblO.Single(key: id); /* get the order record */
order.OrderDate = DateTime.Today; /* update order's fields */
/* more updates if needed */
saveList.Add(tblO.CreateUpdateCommand(order, id)); /* add Order to command list */
/* now delete some existing order lines */
var lines2Delete = "25, 31, 33" // let's assume some comma separated Ids
var tblL = new OrderLines();
saveList.Add(tblL.CreateDeleteCommand(string.Format("WHERE Id IN ({0})", lines2Delete)));
/* now add some new Orderlines */
/* for this usually I create a List<dynamic> */
var newLines = new List<dynamic>(); /* add your objects to this list */
/* now add each of those to the List of Save commands using a foreach loop */
/* or LINQ:
saveList.AddRange(newLines.Select(o => tblL.CreateInsertCommand(o).Cast<DbCommand>());
*/
tblO.Execute(saveList); //boom: save everything in a Transaction!
}