1 | using System;
|
---|
2 | using System.Collections.Generic;
|
---|
3 | using System.Linq;
|
---|
4 | using System.Text;
|
---|
5 |
|
---|
6 | namespace HeuristicLab.DataAccess.ADOHelper {
|
---|
7 | public class ManyToManyRelationHelper<AdapterT, RowT>
|
---|
8 | where AdapterT : new()
|
---|
9 | where RowT : System.Data.DataRow
|
---|
10 | {
|
---|
11 | ITableAdapterWrapper<AdapterT, ManyToManyRelation, RowT> tableAdapterWrapper;
|
---|
12 |
|
---|
13 | public ManyToManyRelationHelper(
|
---|
14 | ITableAdapterWrapper<AdapterT, ManyToManyRelation, RowT> tableAdapterWrapper) {
|
---|
15 | this.tableAdapterWrapper = tableAdapterWrapper;
|
---|
16 | }
|
---|
17 |
|
---|
18 | public Session Session {
|
---|
19 | set {
|
---|
20 | tableAdapterWrapper.Session = value;
|
---|
21 | }
|
---|
22 | }
|
---|
23 |
|
---|
24 | public void UpdateRelationships(Guid objectA, IList<Guid> relationships) {
|
---|
25 | //firstly check for created references
|
---|
26 | IList<Guid> existing =
|
---|
27 | this.GetRelationships(objectA);
|
---|
28 |
|
---|
29 | foreach (Guid relationship in relationships) {
|
---|
30 | if (!existing.Contains(relationship)) {
|
---|
31 | ManyToManyRelation rel =
|
---|
32 | new ManyToManyRelation();
|
---|
33 | rel.Id = objectA;
|
---|
34 | rel.Id2 = relationship;
|
---|
35 |
|
---|
36 | RowT inserted =
|
---|
37 | tableAdapterWrapper.InsertNewRow(rel);
|
---|
38 |
|
---|
39 | tableAdapterWrapper.UpdateRow(inserted);
|
---|
40 | }
|
---|
41 | }
|
---|
42 |
|
---|
43 | //secondly check for deleted references
|
---|
44 | ICollection<Guid> deleted =
|
---|
45 | new List<Guid>();
|
---|
46 |
|
---|
47 | foreach (Guid relationship in existing) {
|
---|
48 | if(!relationships.Contains(relationship)) {
|
---|
49 | deleted.Add(relationship);
|
---|
50 | }
|
---|
51 | }
|
---|
52 |
|
---|
53 | foreach (Guid relationship in deleted) {
|
---|
54 | RowT toDelete =
|
---|
55 | FindRow(objectA, relationship);
|
---|
56 | if (toDelete != null) {
|
---|
57 | toDelete.Delete();
|
---|
58 | tableAdapterWrapper.UpdateRow(toDelete);
|
---|
59 | }
|
---|
60 | }
|
---|
61 | }
|
---|
62 |
|
---|
63 | public IList<Guid> GetRelationships(Guid objectA) {
|
---|
64 | IList<Guid> result =
|
---|
65 | new List<Guid>();
|
---|
66 |
|
---|
67 | IEnumerable<RowT> rows =
|
---|
68 | tableAdapterWrapper.FindById(objectA);
|
---|
69 |
|
---|
70 | foreach(RowT row in rows) {
|
---|
71 | result.Add((Guid)row[1]);
|
---|
72 | }
|
---|
73 |
|
---|
74 | return result;
|
---|
75 | }
|
---|
76 |
|
---|
77 | private RowT FindRow(Guid objectA, Guid objectB) {
|
---|
78 | IEnumerable<RowT> rows =
|
---|
79 | tableAdapterWrapper.FindById(objectA);
|
---|
80 |
|
---|
81 | RowT found = null;
|
---|
82 |
|
---|
83 | foreach (RowT row in rows) {
|
---|
84 | if (row[1].Equals(objectB)) {
|
---|
85 | found = row;
|
---|
86 | break;
|
---|
87 | }
|
---|
88 | }
|
---|
89 |
|
---|
90 | return found;
|
---|
91 | }
|
---|
92 | }
|
---|
93 | }
|
---|