comparison Source/Mapping/MapIndex.cs @ 0:f990fcb411a9

Копия текущей версии из github
author cin
date Thu, 27 Mar 2014 21:46:09 +0400
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:f990fcb411a9
1 using System;
2 using System.Linq;
3 using BLToolkit.Common;
4 using BLToolkit.Properties;
5
6 namespace BLToolkit.Mapping
7 {
8 public class MapIndex
9 {
10 public MapIndex(string[] names)
11 {
12 if (null == names)
13 throw new ArgumentNullException("names");
14
15 if (names.Length == 0)
16 throw new ArgumentException(Resources.MapIndex_EmptyNames, "names");
17
18 Fields = NameOrIndexParameter.FromStringArray(names);
19 }
20
21 public MapIndex(int[] indices)
22 {
23 if (null == indices)
24 throw new ArgumentNullException("indices");
25
26 if (indices.Length == 0)
27 throw new ArgumentException(Resources.MapIndex_EmptyIndices, "indices");
28
29 Fields = NameOrIndexParameter.FromIndexArray(indices);
30 }
31
32 public MapIndex(params NameOrIndexParameter[] fields)
33 {
34 if (null == fields)
35 throw new ArgumentNullException("fields");
36
37 if (fields.Length == 0)
38 throw new ArgumentException(Resources.MapIndex_EmptyFields, "fields");
39
40 Fields = fields;
41 }
42
43 public NameOrIndexParameter[] Fields { get; private set; }
44
45 private string _id;
46 public string ID
47 {
48 get { return _id ?? (_id = string.Join(".", Fields.Select(_ => _.ToString()).ToArray())); }
49 }
50
51 [CLSCompliant(false)]
52 public object GetValue(IMapDataSource source, object obj, int index)
53 {
54 if (source == null)
55 throw new ArgumentNullException("source");
56
57 var value = Fields[index].ByName?
58 source.GetValue(obj, Fields[index].Name):
59 source.GetValue(obj, Fields[index].Index);
60
61 if (value == null)
62 {
63 var objectMapper = source as ObjectMapper;
64
65 if (objectMapper != null)
66 {
67 var mm = Fields[index].ByName?
68 objectMapper[Fields[index].Name]: objectMapper[Fields[index].Index];
69
70 if (mm == null)
71 throw new MappingException(string.Format(Resources.MapIndex_BadField,
72 objectMapper.TypeAccessor.OriginalType.Name, Fields[index]));
73 }
74 }
75
76 return value;
77 }
78
79 [CLSCompliant(false)]
80 public object GetValueOrIndex(IMapDataSource source, object obj)
81 {
82 return Fields.Length == 1?
83 GetValue(source, obj, 0):
84 GetIndexValue(source, obj);
85 }
86
87 [CLSCompliant(false)]
88 public CompoundValue GetIndexValue(IMapDataSource source, object obj)
89 {
90 var values = new object[Fields.Length];
91
92 for (var i = 0; i < values.Length; i++)
93 values[i] = GetValue(source, obj, i);
94
95 return new CompoundValue(values);
96 }
97 }
98 }
99