File: MetaForeignKeyColumn.cs

package info (click to toggle)
mono 6.12.0.199%2Bdfsg-6
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 1,296,836 kB
  • sloc: cs: 11,181,803; xml: 2,850,076; ansic: 699,709; cpp: 123,344; perl: 59,361; javascript: 30,841; asm: 21,853; makefile: 20,405; sh: 15,009; python: 4,839; pascal: 925; sql: 859; sed: 16; php: 1
file content (214 lines) | stat: -rw-r--r-- 8,445 bytes parent folder | download | duplicates (9)
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Security.Permissions;
using System.Web.DynamicData.ModelProviders;
using System.Linq;
using System.Web.UI;

namespace System.Web.DynamicData {
    /// <summary>
    /// A special column representing many-1 relationships
    /// </summary>
    public class MetaForeignKeyColumn : MetaColumn, IMetaForeignKeyColumn {
        // Maps a foreign key name to the name that should be used in a Linq expression for filtering
        // i.e. the foreignkey name might be surfaced through a custom type descriptor e.g. CategoryID but we might really want to use
        // Category.CategoryId in the expression
        private Dictionary<string, string> _foreignKeyFilterMapping;

        public MetaForeignKeyColumn(MetaTable table, ColumnProvider entityMember)
            : base(table, entityMember) {
        }

        /// <summary>
        /// Perform initialization logic for this column
        /// </summary>
        internal protected override void Initialize() {
            base.Initialize();

            ParentTable = Model.GetTable(Provider.Association.ToTable.Name, Table.DataContextType);

            CreateForeignKeyFilterMapping(ForeignKeyNames, ParentTable.PrimaryKeyNames, (foreignKey) => Table.EntityType.GetProperty(foreignKey) != null);
        }

        internal void CreateForeignKeyFilterMapping(IList<string> foreignKeyNames, IList<string> primaryKeyNames, Func<string, bool> propertyExists) {
            // HACK: Some tests don't mock foreign key names, but this should never be the case at runtime
            if (foreignKeyNames == null) {
                return;
            }

            int pKIndex = 0;
            foreach (string fkName in foreignKeyNames) {
                if (!propertyExists(fkName)) {
                    if (_foreignKeyFilterMapping == null) {
                        _foreignKeyFilterMapping = new Dictionary<string, string>();
                    }
                    _foreignKeyFilterMapping[fkName] = Name + "." + primaryKeyNames[pKIndex];
                }
                pKIndex++;
            }
        }

        /// <summary>
        /// The parent table of the relationship (e.g. Categories in Products-&gt;Categories)
        /// </summary>
        public MetaTable ParentTable {
            get;
            // internal for unit testing
            internal set;
        }

        /// <summary>
        /// Returns true if this foriegn key column is part of the primary key of its table
        /// e.g. Order and Product are PKs in the Order_Details table
        /// </summary>
        public bool IsPrimaryKeyInThisTable {
            get {
                return Provider.Association.IsPrimaryKeyInThisTable;
            }
        }

        /// <summary>
        /// This is used when saving the value of a foreign key, e.g. when selected from a drop down.
        /// </summary>
        public void ExtractForeignKey(IDictionary dictionary, string value) {
            if (String.IsNullOrEmpty(value)) {
                // If the value is null, set all the FKs to null
                foreach (string fkName in ForeignKeyNames) {
                    dictionary[fkName] = null;
                }
            }
            else {
                string[] fkValues = Misc.ParseCommaSeparatedString(value);
                Debug.Assert(fkValues.Length == ForeignKeyNames.Count);
                for (int i = 0; i < fkValues.Length; i++) {
                    dictionary[ForeignKeyNames[i]] = fkValues[i];
                }
            }
        }

        /// <summary>
        /// Return the value of all the foreign keys components for the passed in row
        /// </summary>
        public IList<object> GetForeignKeyValues(object row) {
            object[] values = new object[ForeignKeyNames.Count];

            int index = 0;
            bool hasNonNullKey = false;
            foreach (string fkMemberName in ForeignKeyNames) {
                object keyValue = Table.Provider.EvaluateForeignKey(row, fkMemberName);

                // Set a flag if at least one non-null key is found
                if (keyValue != null)
                    hasNonNullKey = true;

                values[index++] = keyValue;
            }

            // If all the foreign keys are null, return null
            if (!hasNonNullKey)
                return null;

            return values;
        }

        /// <summary>
        /// Get a comma separated list of values representing the foreign key 
        /// </summary>
        /// <param name="row"></param>
        /// <returns></returns>
        public string GetForeignKeyString(object row) {
            // Don't do anything if the row is null
            if (row == null) {
                return String.Empty;
            }
            return Misc.PersistListToCommaSeparatedString(GetForeignKeyValues(row));
        }

        /// <summary>
        /// Override allowing for sorting by the display column of the parent table (e.g. in the Products table, the Category column
        /// will be sorted by the Category.Name column order)
        /// </summary>
        internal override string SortExpressionInternal {
            get {
                var displayColumn = ParentTable.DisplayColumn;
                var sortExpression = Provider.Association.GetSortExpression(displayColumn.Provider);
                return sortExpression ?? String.Empty;
            }
        }

        /*protected*/ internal override bool ScaffoldNoCache {
            get {
                // always display many-1 associations
                return true;
            }
        }

        public string GetFilterExpression(string foreignKeyName) {
            string mappedforeignKey;
            // If the mapping doesn't exists for this property then we return the actual FK
            if (_foreignKeyFilterMapping == null || !_foreignKeyFilterMapping.TryGetValue(foreignKeyName, out mappedforeignKey)) {
                return foreignKeyName;
            }

            return mappedforeignKey;
        }

        /// <summary>
        /// Shortcut for getting the path to the details action for the given row
        /// </summary>
        /// <param name="row"></param>
        /// <returns></returns>
        public string GetForeignKeyDetailsPath(object row) {
            return GetForeignKeyPath(PageAction.Details, row);
        }

        public string GetForeignKeyPath(string action, object row) {
            return GetForeignKeyPath(action, row, null);
        }

        public string GetForeignKeyPath(string action, object row, string path) {

            // If there is no row, we can't get a path
            if (row == null)
                return String.Empty;

            // Get the value of all the FKs
            IList<object> fkValues = GetForeignKeyValues(row);

            // If null, there is no associated object to go to
            if (fkValues == null)
                return String.Empty;

            return GetForeignKeyMetaTable(row).GetActionPath(action, fkValues, path);
        }

        internal MetaTable GetForeignKeyMetaTable(object row) {
            // Get the foreign key reference
            object foreignKeyReference = DataBinder.GetPropertyValue(row, Name);
            // if the type is different to the parent table type then proceed to get the correct table
            if (foreignKeyReference != null) {
                // Get the correct MetaTable based on the live object. This is used for inheritance scenarios where the type of the navigation
                // property's parent table is some base type but the instance is pointing to a derived type.
                Type rowType = foreignKeyReference.GetType();
                MetaTable rowTable = Misc.GetTableFromTypeHierarchy(rowType);
                if (rowTable != null) {
                    return rowTable;
                }
            }
            return ParentTable;
        }

        /// <summary>
        /// The names of the underlying foreign keys that make up this association
        /// </summary>
        public ReadOnlyCollection<string> ForeignKeyNames { get { return Provider.Association.ForeignKeyNames; } }

        IMetaTable IMetaForeignKeyColumn.ParentTable {
            get {
                return ParentTable;
            }
        }
    }
}