public int Insert <TDataObject>(TDataObject obj) where TDataObject : class, IIntKeyedDataObject, new() { using (var scope = DBScope("Inserting " + typeof(TDataObject).Name)) { using (var cmd = scope.Connection.CreateCommand()) { var sc = new SqlSerializationContext(cmd); DataObjectSqlSerializer <TDataObject> .AppendInsertSql(sc, obj); sc.Finish(); using (var r = cmd.LexExecuteReader()) { r.Read(); var id = Convert.ToInt32(r.GetDecimal(0)); DataObjectSqlSerializer <TDataObject> .KeyColumn.Storage.SetValue(obj, id); Logger.WriteLine("ID = " + id); Added <TDataObject>(); return(id); } } } }
public void Insert <TDataObject>(IList <TDataObject> objs) where TDataObject : class, IIntKeyedDataObject, new() { if (objs.Count > 0) { using (var scope = DBScope("Inserting multiple " + typeof(TDataObject).Name + ". Count = " + objs.Count)) { RunInTransaction(scope.Connection, (cn, transaction) => { using (var cmd = cn.CreateCommand()) { cmd.Transaction = transaction; var sc = new SqlSerializationContext((SqlCommand)cmd); foreach (var o in objs) { if (o.ID != 0) { throw new DMError("DataObject has been already inserted."); } DataObjectSqlSerializer <TDataObject> .AppendInsertSql(sc, o); sc.Next(); } sc.Finish(); using (var r = cmd.LexExecuteReader()) { int i = 0, c = objs.Count; while (true) { if (!r.Read()) { throw new DMError("Invalid Data Reader"); } int id = Convert.ToInt32(r.GetDecimal(0)); TDataObject obj = objs[i]; DataObjectSqlSerializer <TDataObject> .KeyColumn.Storage.SetValue(obj, id); CacheIt(obj); Added <TDataObject>(); Logger.WriteLine("ID = " + id); ++i; if (i < c) { r.NextResult(); } else { break; } } } } }); } } }