/
Poco.cs
411 lines (363 loc) · 14.5 KB
/
Poco.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
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
#define odataV3
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml;
using OData2Poco.Extensions;
using OData2Poco.InfraStructure.Logging;
#if odataV3
using Microsoft.Data.Edm.Validation;
using Microsoft.Data.Edm.Library.Values;
using Microsoft.Data.Edm;
using Microsoft.Data.Edm.Csdl;
#else
using Microsoft.OData.Edm.Validation;
using Microsoft.OData.Edm;
using Microsoft.OData.Edm.Csdl;
using ISchemaType = Microsoft.OData.Edm.IEdmSchemaType;
#if !EDM7
using Microsoft.OData.Edm.Library.Values;
#endif
#endif
#if odataV3
namespace OData2Poco.V3
#else
namespace OData2Poco.V4
#endif
{
/// <summary>
/// Process metadataString and generate list of classes
/// </summary>
internal partial class Poco : IPocoGenerator
{
private readonly PocoSetting _setting;
public MetaDataInfo MetaData { get; set; }
public string MetaDataAsString => MetaData.MetaDataAsString;
private IEnumerable<IEdmEntitySet> EntitySets { get; set; }
private readonly ILog _logger = PocoLogger.Default;
private List<string> SchemaErrors { get; set; }
private IEdmModel Model { get; set; } = null!;
internal Poco(MetaDataInfo metaData, PocoSetting setting)
{
_setting = setting ?? new PocoSetting();
MetaData = metaData;
SchemaErrors = new List<string>();
EntitySets = new List<IEdmEntitySet>();
}
#if odataV3
internal virtual IEdmModel LoadModelFromString()
{
var tr = new StringReader(MetaDataAsString);
Model = EdmxReader.Parse(XmlReader.Create(tr));
EntitySets = GetEntitySets(Model);
return Model;
}
#else
//support Odata.Edm v7+
internal virtual IEdmModel LoadModelFromString()
{
IEdmModel model2;
//Microsoft.OData.Edm" v7+
//breaking change in Odata.Edm in v7+
var tr = new StringReader(MetaDataAsString);
var reader = XmlReader.Create(tr);
//IEnumerable<EdmError> errors = null;
try
{
#if EDM7
CsdlReader
#else
EdmxReader
#endif
.TryParse(reader, true, out model2, out _); // IgnoreUnexpectedElementsAndAttributes
// .TryParse(reader, true, out model2, out errors);
EntitySets = GetEntitySets(model2);
}
finally
{
((IDisposable)reader).Dispose();
}
return model2;
}
#endif
private List<string> GetEnumElements(IEdmSchemaType type, out bool isFlags)
{
var enumList = new List<string>();
isFlags = false;
if (type.TypeKind != EdmTypeKind.Enum) return enumList;
if (!(type is IEdmEnumType enumType)) return enumList;
var list2 = enumType.Members;
isFlags = enumType.IsFlags;
foreach (var item in list2)
{
#if odataV3
var enumValue = ((EdmIntegerConstant)item.Value).Value;
var enumElement = $"\t\t{item.Name}={enumValue}";
#else
#if EDM7
//issue12 reserved keyword
var enumElement = $"\t\t{item.Name.ChangeReservedWord()}={item.Value.Value}";
//var enumElement = $"\t\t{item.Name}={item.Value.Value}";
#else
var enumValue = ((EdmIntegerConstant)item.Value).Value;
var enumElement = $"\t\t{item.Name.ChangeReservedWord()}={enumValue}";
//var enumElement = $"\t\t{item.Name}={enumValue}";
#endif
#endif
//enumList.Add(item.Name); // v2.3.0
enumList.Add(enumElement); //issue #7 complete enum name /value
}
return enumList;
}
private string GetEntitySetName(IEdmSchemaType ct)
{
if (ct.TypeKind != EdmTypeKind.Entity)
return string.Empty;
#if odataV3
var entitySet = EntitySets
.Where(m => m != null && m.ElementType.FullName() == ct.FullName())
.DefaultIfEmpty().First();
#else
var entitySet = EntitySets
.Where(m => m != null && m.EntityType().FullName() == ct.FullName())
.DefaultIfEmpty().First();
#endif
return entitySet != null ? entitySet.Name : string.Empty;
}
internal IEnumerable<IEdmEntitySet> GetEntitySets(IEdmModel model)
{
#if odataV3
var entitySets = model.EntityContainers()
.SelectMany(c => c.Elements)
.Where(x => x.ContainerElementKind == EdmContainerElementKind.EntitySet)
.Select(element => (IEdmEntitySet) element);
return entitySets;
#else
var entitySets = model.EntityContainer.EntitySets();
return entitySets;
#endif
}
/// <summary>
/// Fill List with class name and properties of corresponding entitie to be used for generating code
/// </summary>
/// <returns></returns>
public List<ClassTemplate> GeneratePocoList()
{
var list = new List<ClassTemplate>();
var model2 = LoadModelFromString();
IEnumerable<IEdmSchemaType> schemaElements = GetSchemaElements(model2);
foreach (var type in schemaElements.ToList())
{
var ct = GeneratePocoClass(type);
if (ct == null) continue;
list.Add(ct);
}
return list;
}
internal ClassTemplate? GeneratePocoClass(IEdmSchemaType ent)
{
if (ent == null) return null;
var className = ent.Name;
var classTemplate = new ClassTemplate
{
Name = className,
OriginalName = className,
IsEnum = ent is IEdmEnumType,
NameSpace = ent.Namespace,
};
switch (ent)
{
case IEdmEnumType enumType:
{
classTemplate.EnumElements = GetEnumElements(enumType, out var isFlags); //fill enum elements for enumtype
classTemplate.IsFlags = isFlags;
return classTemplate;
}
case IEdmEntityType entityType:
{
classTemplate.IsEntity = true;
classTemplate.IsAbstrct = entityType.IsAbstract;
// Set base type by default
var baseEntityType = entityType.BaseEntityType();
if (baseEntityType != null) classTemplate.BaseType = baseEntityType.FullName(); //.Name
classTemplate.EntitySetName = GetEntitySetName(ent);
break;
}
//parent of complex types
case IEdmComplexType complexType:
{
classTemplate.IsComplex = true;
classTemplate.IsAbstrct = complexType.IsAbstract;
if (complexType.BaseType != null)
classTemplate.BaseType = complexType.BaseType.ToString()??"";
break;
}
default:
return null;
}
//fill keys
var list = GetKeys(ent);
if (list != null) classTemplate.Keys.AddRange(list);
//fill navigation properties
var list2 = GetNavigation(ent);
if (list2 != null) classTemplate.Navigation.AddRange(list2);
var entityProperties = GetClassProperties(ent);
//set the key ,comment
foreach (var property in entityProperties)
{
property.ClassName = className;
property.OriginalName = property.PropName;
if (classTemplate.Navigation.Exists(x => x == property.PropName)) property.IsNavigate = true;
if (classTemplate.Keys.Exists(x => x == property.PropName)) property.IsKey = true;
var comment = (property.IsKey ? "PrimaryKey" : string.Empty)
+ (property.IsNullable ? string.Empty : " not null");
if (!string.IsNullOrEmpty(comment)) property.PropComment = comment;
}
classTemplate.Properties.AddRange(entityProperties);
return classTemplate;
}
private List<string> GetNavigation(IEdmSchemaType ent)
{
var list = new List<string>();
if (!(ent is IEdmEntityType entityType)) return list;
var nav = entityType.DeclaredNavigationProperties().ToList();
list.AddRange(nav.Select(key => key.Name));
return list;
}
private List<string> GetKeys(IEdmSchemaType ent)
{
var list = new List<string>();
if (!(ent is IEdmEntityType entityType)) return list;
var keys = entityType.DeclaredKey;
if (keys != null)
list.AddRange(keys.Select(key => key.Name));
return list;
}
private List<PropertyTemplate> GetClassProperties(IEdmSchemaType ent)
{
//stop here if enum
if (ent is IEdmEnumType) return Enumerable.Empty<PropertyTemplate>().ToList(); //null;
var structuredType = ent as IEdmStructuredType;
var properties = structuredType.Properties();
if (_setting != null && _setting.UseInheritance)
{
#if odataV3
properties = properties.Where(x => ((IEdmSchemaType)x.DeclaringType).FullName() == ent.FullName());
#else
properties = properties.Where(x => x.DeclaringType.FullTypeName() == ent.FullTypeName());
#endif
}
//add serial for properties to support protbuf v3.0
var serial = 1;
var list = properties.Select(property => new PropertyTemplate
{
IsNullable = property.Type.IsNullable,
PropName = property.Name,
PropType = GetClrTypeName(property.Type),
Serial = serial++,
ClassNameSpace = ent.Namespace,
MaxLength = GetMaxLength(property),
IsReadOnly = Model.IsReadOnly(property),
}).ToList();
return list;
}
int? GetMaxLength(IEdmProperty property)
{
int? maxLength = null;
switch (property.Type.PrimitiveKind())
{
case EdmPrimitiveTypeKind.String:
maxLength = property.Type.AsString().MaxLength;
break;
case EdmPrimitiveTypeKind.Binary:
maxLength = property.Type.AsBinary().MaxLength;
break;
}
//property.Type.AsDecimal().Precision
return maxLength ?? 0;
}
//fill all properties/name of the class template
private string GetClrTypeName(IEdmTypeReference edmTypeReference)
{
//CheckError(edmTypeReference);
CheckError(edmTypeReference);
var clrTypeName = edmTypeReference.ToString()??"UNDEFINED";
var edmType = edmTypeReference.Definition;
if (edmTypeReference.IsPrimitive())
if (edmType != null)
return EdmToClr((IEdmPrimitiveType) edmType);
if (edmTypeReference.IsEnum())
{
if (edmType is IEdmEnumType ent)
return ent.FullName();
}
if (edmTypeReference.IsComplex())
{
if (edmType is IEdmComplexType edmComplexType)
return edmComplexType.FullName();
}
if (edmTypeReference.IsEntity())
{
if (edmType is IEdmEntityType ent)
return ent.FullName();
}
if (edmTypeReference.IsEntityReference())
{
if (edmType is IEdmEntityType ent)
return ent.FullName();
}
if (!edmTypeReference.IsCollection()) return clrTypeName;
if (!(edmType is IEdmCollectionType edmCollectionType)) return clrTypeName;
var elementTypeReference = edmCollectionType.ElementType;
if (!(elementTypeReference.Definition is IEdmPrimitiveType primitiveElementType))
{
if (!(elementTypeReference.Definition is IEdmSchemaElement schemaElement)) return clrTypeName;
clrTypeName = schemaElement.FullName();
clrTypeName = $"List<{clrTypeName}>";
return clrTypeName;
}
clrTypeName = EdmToClr(primitiveElementType);
clrTypeName = $"List<{clrTypeName}>";
return clrTypeName;
}
private string EdmToClr(IEdmPrimitiveType type)
{
var kind = type.PrimitiveKind;
return ClrDictionary.ContainsKey(kind)
? ClrDictionary[kind]
: kind.ToString();
}
private bool CheckError(IEdmTypeReference edmTypeReference)
{
var edmType = edmTypeReference.Definition;
if (!edmType.Errors().Any()) return false;
var error = edmType.Errors().Select(x => $"Location: {x.ErrorLocation}, {x.ErrorMessage }").FirstOrDefault();
_logger.Trace($"edmTypeReference Error: {error.Dump()}");
_logger.Warn($"Invalid Type Reference: {edmType}");
SchemaErrors.Add($"Invalid Type Reference: {edmType}");
return true;
}
#region Helper Methods
internal IEdmSchemaType? GetSchemaType(string name, string nameSpace)
{
return (IEdmSchemaType?)Model.SchemaElements
.FirstOrDefault(x => x.Name == name && x.Namespace == nameSpace);
}
internal IEdmSchemaType? GetSchemaType(string fullName)
{
return (IEdmSchemaType?)Model.SchemaElements
.FirstOrDefault(x => x.FullName() == fullName);
}
IEnumerable<IEdmSchemaType> GetSchemaElements(IEdmModel model)
{
return model.SchemaElements.OfType<IEdmSchemaType>();
}
internal IEnumerable<IEdmSchemaType> GetSchemaElements(Func<IEnumerable<IEdmSchemaType>, IEnumerable<IEdmSchemaType>> func)
{
var elements = Model.SchemaElements.OfType<IEdmSchemaType>();
return func(elements);
}
#endregion
}
}