-
Notifications
You must be signed in to change notification settings - Fork 2
/
XpoImportHelper.cs
72 lines (67 loc) · 2.55 KB
/
XpoImportHelper.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
using DevExpress.Xpo;
using DevExpress.Xpo.Helpers;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DevExpress.Sample {
public abstract class XpoImportHelper {
private IDataLayer dataLayer;
private ICommandChannel commandChannel;
private int batchSize;
public XpoImportHelper(IDataLayer dataLayer, int batchSize) {
this.dataLayer = dataLayer;
this.commandChannel = dataLayer as ICommandChannel;
this.batchSize = batchSize;
}
protected abstract object CreatePersistentObject(Session session, object sourceObject);
public void Import(IEnumerable sourceObjects) {
if (commandChannel != null) {
ImportInBatches(sourceObjects);
} else {
ImportAtOnce(sourceObjects);
}
}
private void ImportAtOnce(IEnumerable sourceObjects) {
using (UnitOfWork uow = new UnitOfWork(dataLayer)) {
foreach (object current in sourceObjects) {
object obj = CreatePersistentObject(uow, current);
uow.Save(obj);
}
uow.CommitChanges();
}
}
private void ImportInBatches(IEnumerable sourceObjects) {
commandChannel.Do(CommandChannelHelper.Command_ExplicitBeginTransaction, null);
UnitOfWork uow = null;
try {
int i = 0;
IEnumerator enumerator = sourceObjects.GetEnumerator();
bool more = enumerator.MoveNext();
while (more) {
if (uow == null) {
uow = new UnitOfWork(dataLayer);
}
object obj = CreatePersistentObject(uow, enumerator.Current);
uow.Save(obj);
more = enumerator.MoveNext();
i++;
if (!more || i >= batchSize) {
uow.CommitChanges();
uow.Dispose();
uow = null;
i = 0;
}
}
commandChannel.Do(CommandChannelHelper.Command_ExplicitCommitTransaction, null);
} catch (Exception ex) {
if (uow != null) {
uow.Dispose();
}
commandChannel.Do(CommandChannelHelper.Command_ExplicitRollbackTransaction, null);
throw ex;
}
}
}
}