/
EF.Reverse.POCO.v3.ttinclude
18539 lines (16103 loc) · 735 KB
/
EF.Reverse.POCO.v3.ttinclude
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<#
// Copyright (C) Simon Hughes 2012
// v3.1.3
// If you want to submit a pull request, please modify the Generator C# project as this file
// is automatically constructed from the C# Generator project during the build process.
#>
<#@ template debug="true" hostspecific="true" language="C#" #>
<#@ include file="EF6.Utility.CS.ttinclude"#><#@ assembly name="System.Configuration" #>
<#@ assembly name="System.Windows.Forms" #>
<#@ import namespace="System.Data.Entity.Infrastructure.Pluralization" #>
<#@ import namespace="System" #>
<#@ import namespace="System.Collections" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.ComponentModel" #>
<#@ import namespace="System.Data" #>
<#@ import namespace="System.Data.Common" #>
<#@ import namespace="System.Data.SqlClient" #>
<#@ import namespace="System.Diagnostics" #>
<#@ import namespace="System.Globalization" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Reflection" #>
<#@ import namespace="System.Security" #>
<#@ import namespace="System.Security.Cryptography" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Text.RegularExpressions" #>
<#@ import namespace="EnvDTE" #>
<#@ import namespace="Microsoft.VisualStudio.TextTemplating" #>
<#@ output extension=".cs" encoding="utf-8" #>
<#
var DefaultNamespace = new CodeGenerationTools(this).VsNamespaceSuggestion() ?? "DebugMode";
Settings.Root = Host.ResolvePath(string.Empty);
#><#+
public static class Settings
{
// Main settings **********************************************************************************************************************
// The following entries are the only required settings.
public static DatabaseType DatabaseType = DatabaseType.SqlServer; // SqlServer, SqlCe. Coming next: PostgreSQL, MySql, Oracle
public static TemplateType TemplateType = TemplateType.EfCore3; // Ef6, EfCore2, EfCore3, FileBasedCore2, FileBasedCore3. FileBased specify folder using Settings.TemplateFolder
public static GeneratorType GeneratorType = GeneratorType.EfCore; // Ef6, EfCore, Custom. Custom edit GeneratorCustom class to provide your own implementation
public static bool UseMappingTables = false; // Set to false for EfCore. EFCore will add support for this in v3 at some point, so please set this to false. If true, mapping will be used and no mapping tables will be generated. If false, all tables will be generated.
public static FileManagerType FileManagerType = FileManagerType.Custom; // .NET project = VisualStudio; .NET Core project = Custom; No output (testing only) = Null
public static string ConnectionString = ""; // This is used by the generator to reverse engineer your database
public static string ConnectionStringName = "MyDbContext"; // ConnectionString key as specified in your app.config/web.config/appsettings.json
public static string DbContextName = "MyDbContext"; // Class name for the DbContext to be generated. Note: If generating separate files, please give the db context a different name from this tt filename. Ignored if using multi-context generation
public static bool GenerateSeparateFiles = false;
public static string Namespace = typeof(Settings).Namespace; // Override the default namespace here. Example: Namespace = "CustomNamespace";
public static string TemplateFolder = ""; // Only used if Settings.TemplateType = TemplateType.FileBased. Specify folder name where the mustache folders can be found. Please read https://github.com/sjh37/EntityFramework-Reverse-POCO-Code-First-Generator/wiki/Custom-file-based-templates
public static bool AddUnitTestingDbContext = true; // Will add a FakeDbContext and FakeDbSet for easy unit testing
// Elements to generate ***************************************************************************************************************
// Add the elements that should be generated when the template is executed.
// Multiple projects can now be used that separate the different concerns.
public static Elements ElementsToGenerate = Elements.Poco | Elements.Context | Elements.Interface | Elements.PocoConfiguration | Elements.Enum;
public static int CommandTimeout = 600; // SQL Command timeout in seconds. 600 is 10 minutes, 0 will wait indefinitely. Some databases can be slow retrieving schema information.
public static string DbContextInterfaceBaseClasses = "IDisposable"; // Specify what the base classes are for your database context interface
public static string DbContextBaseClass = "DbContext"; // Specify what the base class is for your DbContext. For ASP.NET Identity use "IdentityDbContext<ApplicationUser>";
public static OnConfiguration OnConfiguration = OnConfiguration.ConnectionString; // EFCore only. Determines the code generated within DbContext.OnConfiguration(). Please read https://github.com/sjh37/EntityFramework-Reverse-POCO-Code-First-Generator/wiki/Settings.OnConfiguration
public static bool AddParameterlessConstructorToDbContext = true; // If true, then DbContext will have a default (parameter-less) constructor which automatically passes in the connection string name, if false then no parameter-less constructor will be created.
public static string ConfigurationClassName = "Configuration"; // Configuration, Mapping, Map, etc. This is appended to the Poco class name to configure the mappings.
public static string DatabaseReaderPlugin = ""; // Eg, "c:\\Path\\YourDatabaseReader.dll,Full.Name.Of.Class.Including.Namespace". See #501. This will allow you to specify a pluggable provider for reading your database.
public static string EntityClassesModifiers = "public"; // "public partial";
public static string ConfigurationClassesModifiers = "public"; // "public partial";
public static string DbContextClassModifiers = "public"; // "public partial";
public static string DbContextInterfaceModifiers = "public"; // "public partial";
public static string ResultClassModifiers = "public"; // "public partial";
public static bool UsePascalCase = true; // This will rename the generated C# tables & properties to use PascalCase. If false table & property names will be left alone.
public static bool UseDataAnnotations = false; // If true, will add data annotations to the poco classes.
public static bool UsePropertyInitialisers = false; // Removes POCO constructor and instead uses C# 6 property initialisers to set defaults
public static bool UseLazyLoading = true; // Marks all navigation properties as virtual or not, to support or disable EF Lazy Loading feature
public static bool UseInheritedBaseInterfaceFunctions = false; // If true, the main DBContext interface functions will come from the DBContextInterfaceBaseClasses and not generated. If false, the functions will be generated.
public static CommentsStyle IncludeComments = CommentsStyle.AtEndOfField; // Adds comments to the generated code
public static CommentsStyle IncludeExtendedPropertyComments = CommentsStyle.InSummaryBlock; // Adds extended properties as comments to the generated code
public static bool DisableGeographyTypes = false; // Turns off use of System.Data.Entity.Spatial.DbGeography and System.Data.Entity.Spatial.DbGeometry as OData doesn't support entities with geometry/geography types.
public static string CollectionInterfaceType = "ICollection"; // = "System.Collections.Generic.List"; // Determines the declaration type of collections for the Navigation Properties. ICollection is used if not set.
public static string CollectionType = "List"; // Determines the type of collection for the Navigation Properties. "ObservableCollection" for example. Add "System.Collections.ObjectModel" to AdditionalNamespaces if setting the CollectionType = "ObservableCollection".
public static bool NullableShortHand = true; // true => T?, false => Nullable<T>
public static bool AddIDbContextFactory = true; // Will add a default IDbContextFactory<DbContextName> implementation for easy dependency injection
public static bool IncludeQueryTraceOn9481Flag = false; // If SqlServer 2014 appears frozen / take a long time when this file is saved, try setting this to true (you will also need elevated privileges).
public static bool UsePrivateSetterForComputedColumns = true; // If the columns is computed, use a private setter.
public static bool IncludeGeneratorVersionInCode = false; // If true, will include the version number of the generator in the generated code
public static List<string> AdditionalNamespaces = new List<string>(); // To include extra namespaces, include them here. i.e. "Microsoft.AspNet.Identity.EntityFramework"
public static List<string> AdditionalContextInterfaceItems = new List<string>(); // example: "void SetAutoDetectChangesEnabled(bool flag);"
// Language choices
public static GenerationLanguage GenerationLanguage = GenerationLanguage.CSharp;
public static string FileExtension = ".cs";
// Code suppression *******************************************************************************
public static bool UseRegions = true; // If false, suppresses the use of #region
public static bool UseNamespace = true; // If false, suppresses the writing of a namespace
public static bool UsePragma = false; // If false, suppresses the writing of #pragma
public static bool AllowNullStrings = false; // If true, will allow string? properties and will add '#nullable enable' to the top of each file
public static bool UseResharper = false; // If true, will add a list of 'ReSharper disable' comments to the top of each file
public static bool ShowLicenseInfo = false; // If true, will add the licence info comment to the top of each file
public static bool IncludeConnectionSettingComments = false; // Add comments describing connection settings used to generate file
public static bool IncludeCodeGeneratedAttribute = false; // If true, will include the [GeneratedCode] attribute before classes, false to remove it.
// Create enumerations from database tables
// List the enumeration tables you want read and generated for
public static List<EnumerationSettings> Enumerations = new List<EnumerationSettings>
{
// Example
/*new EnumerationSettings
{
Name = "DaysOfWeek", // Enum to generate. e.g. "DaysOfWeek" would result in "public enum DaysOfWeek {...}"
Table = "EnumTest.DaysOfWeek", // Database table containing enum values. e.g. "DaysOfWeek"
NameField = "TypeName", // Column containing the name for the enum. e.g. "TypeName"
ValueField = "TypeId" // Column containing the values for the enum. e.g. "TypeId"
},
new EnumerationSettings
{
Name = "CarOptions",
Table = "car_options",
NameField = "enum_name",
ValueField = "value"
}*/
// Code will be generated as:
// public enum Name
// {
// NameField = ValueField,
// etc
// }
};
// If you need to serialise your entities with the JsonSerializer from Newtonsoft, this would serialise
// all properties including the Reverse Navigation and Foreign Keys. The simplest way to exclude them is
// to use the data annotation [JsonIgnore] on reverse navigation and foreign keys.
// For more control, take a look at ForeignKeyAnnotationsProcessing() further down
public static string[] AdditionalReverseNavigationsDataAnnotations = new string[]
{
// "JsonIgnore" // Also add "Newtonsoft.Json" to the AdditionalNamespaces array above
};
public static string[] AdditionalForeignKeysDataAnnotations = new string[]
{
// "JsonIgnore" // Also add "Newtonsoft.Json" to the AdditionalNamespaces array above
};
// Use these namespaces to specify where the different elements now live. These may even be in different assemblies.
// NOTE: These are only used if ElementsToGenerate is not set to generate everything.
// Please note this does not create the files in these locations, it only adds a using statement to say where they are.
// The way to do this is to add the "EntityFramework Reverse POCO Code First Generator" into each of these folders.
// Then set the .tt to only generate the relevant section you need by setting
// ElementsToGenerate = Elements.Poco; in your Entity folder,
// ElementsToGenerate = Elements.Context | Elements.Interface; in your Context folder,
// ElementsToGenerate = Elements.PocoConfiguration; in your Configuration folder.
// You also need to set the following to the namespace where they now live:
public static string PocoNamespace = ""; // "YourProject.Entities";
public static string ContextNamespace = ""; // "YourProject.Context";
public static string InterfaceNamespace = ""; // "YourProject.Context";
public static string PocoConfigurationNamespace = ""; // "YourProject.Configuration";
// Schema *****************************************************************************************************************************
// If there are multiple schemas, then the table name is prefixed with the schema, except for dbo.
// Ie. dbo.hello will be Hello.
// abc.hello will be AbcHello.
public static bool PrependSchemaName = true; // Control if the schema name is prepended to the table name
public static string DefaultSchema = null; // Set via DatabaseReader.DefaultSchema()
// Table Suffix ***********************************************************************************************************************
// Appends the suffix to the generated classes names
// Ie. If TableSuffix is "Dto" then Order will be OrderDto
// If TableSuffix is "Entity" then Order will be OrderEntity
public static string TableSuffix = null;
// AddRelationship is a helper function that creates ForeignKey objects and adds them to the foreignKeys list
public static Action<IDbContextFilter, Generator, List<ForeignKey>, Tables> AddExtraForeignKeys = delegate (IDbContextFilter filter, Generator gen, List<ForeignKey> foreignKeys, Tables tablesAndViews)
{
// Northwind example:
// [Orders] (Table) to [Invoices] (View) is one-to-many using Orders.OrderID = Invoices.OrderID
// gen.AddRelationship(filter, foreignKeys, tablesAndViews, "orders_to_invoices", Settings.DefaultSchema, "Orders", "OrderID", "dbo", "Invoices", "OrderID", null, null, true);
// [Orders] (Table) to [Orders Qry] (View) is one-to-zeroOrOne ( [Orders].OrderID = [Orders Qry].OrderID )
// gen.AddRelationship(filter, foreignKeys, tablesAndViews, "orders_to_ordersQry", Settings.DefaultSchema, "Orders", "OrderID", "dbo", "Orders Qry", "OrderID", "ParentFkName", "ChildFkName", true);
// [Order Details] (Table) to [Invoices] (View) is one-to-zeroOrOne - but uses a composite-key: ( [Order Details].OrderID,ProductID = [Invoices].OrderID,ProductID )
// gen.AddRelationship(filter, foreignKeys, tablesAndViews, "orderDetails_to_invoices", Settings.DefaultSchema, "Order Details", new[] { "OrderID", "ProductID" }, "dbo", "Invoices", new[] { "OrderID", "ProductID" }, null, null, true);
};
// StoredProcedure return types *******************************************************************************************************
// Override generation of return models for stored procedures that return entities.
// If a stored procedure returns an entity, add it to the list below.
// This will suppress the generation of the return model, and instead return the entity.
// Example: Proc name Return this entity type instead
//StoredProcedureReturnTypes.Add("SalesByYear", "SummaryOfSalesByYear");
public static Dictionary<string, string> StoredProcedureReturnTypes = new Dictionary<string, string>();
// Renaming ***********************************************************************************************************************
// Table renaming (single context generation only) ************************************************************************************
// Use the following function to rename tables such as tblOrders to Orders, Shipments_AB to Shipments, etc.
// Example:
public static Func<string, string, bool, string> TableRename = delegate (string name, string schema, bool isView)
{
// Example
//if (name.StartsWith("tbl"))
// name = name.Remove(0, 3);
//name = name.Replace("_AB", "");
//if(isView)
// name = name + "View";
// If you turn pascal casing off (UsePascalCase = false), and use the pluralisation service, and some of your
// tables names are all UPPERCASE, some words ending in IES such as CATEGORIES get singularised as CATEGORy.
// Therefore you can make them lowercase by using the following
//return Inflector.MakeLowerIfAllCaps(name);
// If you are using the pluralisation service and you want to rename a table, make sure you rename the table to the plural form.
// For example, if the table is called Treez (with a z), and your pluralisation entry is
// new CustomPluralizationEntry("Tree", "Trees")
// Use this TableRename function to rename Treez to the plural (not singular) form, Trees:
//if (name == "Treez") return "Trees";
return name;
};
// Use the following function if you need to apply additional modifications to a table
// Called just before UpdateColumn
public static Action<Table> UpdateTable = delegate (Table table)
{
// Add an extra comment
//if (table.NameHumanCase.Equals("SomeTable", StringComparison.InvariantCultureIgnoreCase))
// table.AdditionalComment = "Example comment";
// To add a base class to a table
//if (table.NameHumanCase == "User")
// table.BaseClasses = " : IdentityUser<int, CustomUserLogin, CustomUserRole, CustomUserClaim>";
//if (table.NameHumanCase == "LogData" || table.NameHumanCase == "ReturnData" || table.NameHumanCase == "DataBlob")
// table.BaseClasses = " : ReportData";
// To add attributes
//table.Attributes.Add("[Serializable]");
};
// Use the following function if you need to apply additional modifications to a column
// eg. normalise names etc.
public static Action<Column, Table, List<EnumDefinition>> UpdateColumn = delegate (Column column, Table table, List<EnumDefinition> enumDefinitions)
{
// Rename column
//if (column.IsPrimaryKey && column.NameHumanCase == "PkId")
// column.NameHumanCase = "Id";
// .IsConcurrencyToken() must be manually configured. However .IsRowVersion() can be automatically detected.
//if (table.NameHumanCase.Equals("SomeTable", StringComparison.InvariantCultureIgnoreCase) && column.NameHumanCase.Equals("SomeColumn", StringComparison.InvariantCultureIgnoreCase))
// column.IsConcurrencyToken = true;
// Remove table name from primary key
//if (column.IsPrimaryKey && column.NameHumanCase.Equals(table.NameHumanCase + "Id", StringComparison.InvariantCultureIgnoreCase))
// column.NameHumanCase = "Id";
// Remove column from poco class as it will be inherited from a base class
//if (column.IsPrimaryKey &&
// (
// table.NameHumanCase.Equals("LogData", StringComparison.InvariantCultureIgnoreCase) ||
// table.NameHumanCase.Equals("ReturnData", StringComparison.InvariantCultureIgnoreCase) ||
// table.NameHumanCase.Equals("DataBlob", StringComparison.InvariantCultureIgnoreCase)
// ))
// column.ExistsInBaseClass = true; // If true, does not generate the property for this column as it will exist in a base class
// Use the extended properties to perform tasks to column
//if (column.ExtendedProperty == "HIDE")
// column.Hidden = true; // Hidden means the generator does not generate any code for this column at all.
// Apply the "override" access modifier to a specific column.
//if (column.NameHumanCase == "id")
// column.OverrideModifier = true;
// This will create: public override long id { get; set; }
// Perform Enum property type replacement
var enumDefinition = enumDefinitions?.FirstOrDefault(e =>
(e.Schema.Equals(table.Schema.DbName, StringComparison.InvariantCultureIgnoreCase)) &&
(e.Table == "*" || e.Table.Equals(table.DbName, StringComparison.InvariantCultureIgnoreCase) || e.Table.Equals(table.NameHumanCase, StringComparison.InvariantCultureIgnoreCase)) &&
(e.Column.Equals(column.DbName, StringComparison.InvariantCultureIgnoreCase) || e.Column.Equals(column.NameHumanCase, StringComparison.InvariantCultureIgnoreCase)));
if (enumDefinition != null)
{
column.PropertyType = enumDefinition.EnumType;
if (!string.IsNullOrEmpty(column.Default))
column.Default = "(" + enumDefinition.EnumType + ") " + column.Default;
}
};
// Using Views *****************************************************************************************************************
// SQL Server does not support the declaration of primary-keys in VIEWs. Entity Framework's EDMX designer (and this generator)
// assume that all non-null columns in a VIEW are primary-key columns, this will be incorrect for most non-trivial applications.
// This callback will be invoked for each VIEW found in the database. Use it to declare which columns participate in that VIEW's
// primary-key by setting 'IsPrimaryKey = true'.
// If no columns are marked with 'IsPrimaryKey = true' then this T4 template defaults to marking all non-NULL columns as primary key columns.
// To set-up Foreign-Key relationships between VIEWs and Tables (or even other VIEWs) use the 'AddForeignKeys' callback below.
public static Action<Table> ViewProcessing = delegate (Table view)
{
// Below is example code for the Northwind database that configures the 'VIEW [Orders Qry]' and 'VIEW [Invoices]'
/*switch (view.DbName)
{
case "Orders Qry":
// VIEW [Orders Qry] uniquely identifies rows with the 'OrderID' column:
view.Columns.Single(col => col.DbName == "OrderID").IsPrimaryKey = true;
break;
case "Invoices":
// VIEW [Invoices] has a composite primary key (OrderID+ProductID), so both columns must be marked as a Primary Key:
foreach (var col in view.Columns.Where(c => c.DbName == "OrderID" || c.DbName == "ProductID"))
col.IsPrimaryKey = true;
break;
}*/
};
// StoredProcedure renaming ************************************************************************************************************
// Use the following function to rename stored procs such as sp_CreateOrderHistory to CreateOrderHistory, my_sp_shipments to Shipments, etc.
public static Func<StoredProcedure, string> StoredProcedureRename = delegate (StoredProcedure sp)
{
// Example:
//if (sp.NameHumanCase.StartsWith("sp_"))
// return sp.NameHumanCase.Remove(0, 3);
//return sp.NameHumanCase.Replace("my_sp_", "");
return sp.NameHumanCase; // Do nothing by default
};
// Use the following function to rename the return model automatically generated for stored procedure.
// By default it's <proc_name>ReturnModel.
public static Func<string, StoredProcedure, string> StoredProcedureReturnModelRename = delegate (string name, StoredProcedure sp)
{
// Example:
//if (sp.NameHumanCase.Equals("ComputeValuesForDate", StringComparison.InvariantCultureIgnoreCase))
// return "ValueSet";
//if (sp.NameHumanCase.Equals("SalesByYear", StringComparison.InvariantCultureIgnoreCase))
// return "SalesSet";
return name; // Do nothing by default
};
// Mapping Table renaming *********************************************************************************************************************
// By default, name of the properties created relate to the table the foreign key points to and not the mapping table.
// Use the following function to rename the properties created by ManyToMany relationship tables especially if you have 2 relationships between the same tables.
// Example:
public static Func<string, string, string, string> MappingTableRename = delegate (string mappingTable, string tableName, string entityName)
{
// Example: If you have two mapping tables such as one being UserRequiredSkills snd one being UserOptionalSkills, this would change the name of one property
//if (mappingTable == "UserRequiredSkills" && tableName == "User")
// return "RequiredSkills";
// or if you want to give the same property name on both classes
//if (mappingTable == "UserRequiredSkills")
// return "UserRequiredSkills";
return entityName;
};
public static Func<string, ForeignKey, string, Relationship, short, string> ForeignKeyName = delegate (string tableName, ForeignKey foreignKey, string foreignKeyName, Relationship relationship, short attempt)
{
string fkName;
// 5 Attempts to correctly name the foreign key
switch (attempt)
{
case 1:
// Try without appending foreign key name
fkName = tableName;
break;
case 2:
// Only called if foreign key name ends with "id"
// Use foreign key name without "id" at end of string
fkName = foreignKeyName.Remove(foreignKeyName.Length - 2, 2);
break;
case 3:
// Use foreign key name only
fkName = foreignKeyName;
break;
case 4:
// Use table name and foreign key name
fkName = tableName + "_" + foreignKeyName;
break;
case 5:
// Used in for loop 1 to 99 to append a number to the end
fkName = tableName;
break;
default:
// Give up
fkName = tableName;
break;
}
// Apply custom foreign key renaming rules. Can be useful in applying pluralization.
// For example:
/*if (tableName == "Employee" && foreignKey.FkColumn == "ReportsTo")
return "Manager";
if (tableName == "Territories" && foreignKey.FkTableName == "EmployeeTerritories")
return "Locations";
if (tableName == "Employee" && foreignKey.FkTableName == "Orders" && foreignKey.FkColumn == "EmployeeID")
return "ContactPerson";
*/
// FK_TableName_FromThisToParentRelationshipName_FromParentToThisChildsRelationshipName
// (e.g. FK_CustomerAddress_Customer_Addresses will extract navigation properties "address.Customer" and "customer.Addresses")
// Feel free to use and change the following
/*if (foreignKey.ConstraintName.StartsWith("FK_") && foreignKey.ConstraintName.Count(x => x == '_') == 3)
{
var parts = foreignKey.ConstraintName.Split('_');
if (!string.IsNullOrWhiteSpace(parts[2]) && !string.IsNullOrWhiteSpace(parts[3]) && parts[1] == foreignKey.FkTableName)
{
if (relationship == Relationship.OneToMany)
fkName = parts[3];
else if (relationship == Relationship.ManyToOne)
fkName = parts[2];
}
}*/
return fkName;
};
// This foreign key filter used in addition to SingleContextFilter.ForeignKeyFilter()
// Return null to exclude this foreign key
public static Func<ForeignKey, ForeignKey> ForeignKeyFilterFunc = delegate (ForeignKey fk)
{
// Return null to exclude this foreign key, or set IncludeReverseNavigation = false
// to include the foreign key but not generate reverse navigation properties.
// Example, to exclude all foreign keys for the Categories table, use:
//if (fk.PkTableName == "Categories")
// return null;
// Example, to exclude reverse navigation properties for tables ending with Type, use:
//if (fk.PkTableName.EndsWith("Type"))
// fk.IncludeReverseNavigation = false;
// You can also change the access modifier of the foreign-key's navigation property:
//if(fk.PkTableName == "Categories")
// fk.AccessModifier = "internal";
return fk;
};
public static Func<Table, Table, string, string, string[]> ForeignKeyAnnotationsProcessing = delegate (Table fkTable, Table pkTable, string propName, string fkPropName)
{
// Example:
// Each navigation property that is a reference to User are left intact
//if(pkTable.NameHumanCase.Equals("User") && propName.Equals("User"))
// return null;
// all the others are marked with this attribute
//return new[] { "System.Runtime.Serialization.IgnoreDataMember" };
return null;
};
// Column modification ****************************************************************************************************************
// Use the following list to replace column byte types with Enums.
// As long as the type can be mapped to your new type, all is well.
public static Action<List<EnumDefinition>> AddEnumDefinitions = delegate (List<EnumDefinition> enumDefinitions)
{
// Examples:
//enumDefinitions.Add(new EnumDefinition { Schema = Settings.DefaultSchema, Table = "match_table_name", Column = "match_column_name", EnumType = "name_of_enum" });
// This will replace OrderHeader.OrderStatus type to be an OrderStatusType enum
//enumDefinitions.Add(new EnumDefinition { Schema = Settings.DefaultSchema, Table = "OrderHeader", Column = "OrderStatus", EnumType = "OrderStatusType" });
// This will replace any table *.OrderStatus type to be an OrderStatusType enum
//enumDefinitions.Add(new EnumDefinition { Schema = Settings.DefaultSchema, Table = "*", Column = "OrderStatus", EnumType = "OrderStatusType" });
};
// Generate multiple db contexts in a single go ***************************************************************************************
// Generating multiple contexts at a time requires you specifying which tables, and columns to generate for each context.
// As this generator can now generate multiple db contexts in a single go, filtering is done a per db context, and no longer global.
// If GenerateSingleDbContext = true (default), please modify SingleContextFilter, this is where your previous global settings should go.
// If GenerateSingleDbContext = false, this will generate multiple db contexts. Please read https://github.com/sjh37/EntityFramework-Reverse-POCO-Code-First-Generator/wiki/Generating-multiple-database-contexts-in-a-single-go
public static bool GenerateSingleDbContext = true;
public static string MultiContextSettingsConnectionString = ""; // Leave empty to read data from same database in ConnectionString above. If settings are in another database, specify the connection string here.
public static string MultiContextSettingsPlugin = ""; // Only used for unit testing Generator project as you can't (yet) inherit from IMultiContextSettingsPlugin. "c:\\Path\\YourMultiDbSettingsReader.dll,Full.Name.Of.Class.Including.Namespace". This will allow you to specify a pluggable provider for reading your MultiContext settings.
public static char MultiContextAttributeDelimiter = '~'; // The delimiter used for splitting MultiContext attributes
public static Action<Column, Table, Dictionary<string, object>> MultiContextAllFieldsColumnProcessing = delegate (Column column, Table table, Dictionary<string, object> allFields)
{
// Examples of how to use additional custom fields from the MultiContext.[Column] table
// INT example
/*if (allFields.ContainsKey("DummyInt"))
{
var o = allFields["DummyInt"];
column.ExtendedProperty += string.Format(" DummyInt = {0}", (int) o);
}*/
// VARCHAR example
/*if (allFields.ContainsKey("Test"))
{
var o = allFields["Test"];
column.ExtendedProperty += string.Format(" Test = {0}", o.ToString());
}*/
// DATETIME example
/*if (allFields.ContainsKey("date_of_birth"))
{
var o = allFields["date_of_birth"];
var date = Convert.ToDateTime(o);
column.ExtendedProperty += string.Format(" date_of_birth = {0}", date.ToLongDateString());
}*/
};
public static Action<Table, Dictionary<string, object>> MultiContextAllFieldsTableProcessing = delegate (Table table, Dictionary<string, object> allFields)
{
// Examples of how to use additional custom fields from the MultiContext.[Table] table
// VARCHAR example
/*if (allFields.ContainsKey("Notes"))
{
var o = allFields["Notes"];
if (string.IsNullOrEmpty(table.AdditionalComment))
table.AdditionalComment = string.Empty;
table.AdditionalComment += string.Format(" Test = {0}", o.ToString());
}*/
};
public static Action<StoredProcedure, Dictionary<string, object>> MultiContextAllFieldsStoredProcedureProcessing = delegate (StoredProcedure sp, Dictionary<string, object> allFields)
{
// Examples of how to use additional custom fields from the MultiContext.[Table] table
// VARCHAR example
/*if (allFields.ContainsKey("CustomRename"))
{
var o = allFields["CustomRename"];
sp.NameHumanCase = o.ToString();
}*/
};
public static Action<StoredProcedure, Dictionary<string, object>> MultiContextAllFieldsFunctionProcessing = delegate (StoredProcedure sp, Dictionary<string, object> allFields)
{
// Examples of how to use additional custom fields from the MultiContext.[Table] table
// VARCHAR example
/*if (allFields.ContainsKey("CustomRename"))
{
var o = allFields["CustomRename"];
sp.NameHumanCase = o.ToString();
}*/
};
// Helper functions ***************************************************************************************************************
public static bool DbContextClassIsPartial()
{
return DbContextClassModifiers != null && DbContextClassModifiers.Contains("partial");
}
public static bool EntityClassesArePartial()
{
return EntityClassesModifiers != null && EntityClassesModifiers.Contains("partial");
}
public static bool ConfigurationClassesArePartial()
{
return ConfigurationClassesModifiers != null && ConfigurationClassesModifiers.Contains("partial");
}
private static string _dbContextInterfaceName;
public static string DbContextInterfaceName
{
get { return _dbContextInterfaceName ?? ("I" + DbContextName); }
set { _dbContextInterfaceName = value; }
}
private static bool _explicitDefaultConstructorArgument;
private static string _defaultConstructorArgument;
public static string DefaultConstructorArgument
{
// = null; // Defaults to "Name=" + ConnectionStringName, use null in order not to call the base constructor
get { return _explicitDefaultConstructorArgument ? _defaultConstructorArgument : string.Format('"' + "Name={0}" + '"', ConnectionStringName); }
set { _explicitDefaultConstructorArgument = true; _defaultConstructorArgument = value; }
}
// Don't forget to take a look at SingleContextFilter and FilterSettings classes!
// That's it, nothing else to configure ***********************************************************************************************
public static bool IsEfCore2() => TemplateType == TemplateType.EfCore2 || TemplateType == TemplateType.FileBasedCore2;
public static bool IsEfCore3() => TemplateType == TemplateType.EfCore3 || TemplateType == TemplateType.FileBasedCore3;
public static bool IsEfCore() => IsEfCore2() || IsEfCore3();
public static string Root;
public static int FilterCount;
}
// Filtering **************************************************************************************************************************
// These settings are only used by the single context filter SingleContextFilter (Settings.GenerateSingleDbContext = true)
// Please read https://github.com/sjh37/EntityFramework-Reverse-POCO-Code-First-Generator/wiki/Filtering
// For multi-context filtering (Settings.GenerateSingleDbContext = false), please read https://github.com/sjh37/EntityFramework-Reverse-POCO-Code-First-Generator/wiki/Generating-multiple-database-contexts-in-a-single-go
// Use the following filters to exclude or include schemas/tables/views/columns/stored procedures.
// You can have as many as you like, and mix and match them.
// They run in the order defined below. For help with Regex's try https://regexr.com
// Feel free to add more filter types and include them below.
public static class FilterSettings
{
public static bool IncludeViews;
public static bool IncludeSynonyms;
public static bool IncludeStoredProcedures;
public static bool IncludeTableValuedFunctions;
public static bool IncludeScalarValuedFunctions;
public static readonly List<IFilterType<Schema>> SchemaFilters;
public static readonly List<IFilterType<Table>> TableFilters;
public static readonly List<IFilterType<Column>> ColumnFilters;
public static readonly List<IFilterType<StoredProcedure>> StoredProcedureFilters;
static FilterSettings()
{
SchemaFilters = new List<IFilterType<Schema>>();
TableFilters = new List<IFilterType<Table>>();
ColumnFilters = new List<IFilterType<Column>>();
StoredProcedureFilters = new List<IFilterType<StoredProcedure>>();
}
public static void Reset()
{
SchemaFilters .RemoveAll(x => true);
TableFilters .RemoveAll(x => true);
ColumnFilters .RemoveAll(x => true);
StoredProcedureFilters.RemoveAll(x => true);
}
public static void AddDefaults()
{
IncludeViews = true;
IncludeSynonyms = false;
IncludeStoredProcedures = true;
IncludeTableValuedFunctions = false; // If true, for EF6 install the "EntityFramework.CodeFirstStoreFunctions" NuGet Package.
IncludeScalarValuedFunctions = false;
AddDefaultSchemaFilters();
AddDefaultTableFilters();
AddDefaultColumnFilters();
AddDefaultStoredProcedureFilters();
}
public static void CheckSettings()
{
if (IncludeTableValuedFunctions || IncludeScalarValuedFunctions)
IncludeStoredProcedures = true; // Must be set if table/scalar functions are wanted
}
public static void AddDefaultSchemaFilters()
{
SchemaFilters.AddRange(new List<IFilterType<Schema>>
{
new PeriodFilter(), // Keep this first as EF does not allow schemas to contain a period character
// To include the only the schemas 'dbo' and 'events'
//new RegexIncludeFilter("^dbo$|^events$"),
// Add your own code to these custom filter classes
new SchemaFilter(),
new HasNameFilter(FilterType.Schema)
});
}
public static void AddDefaultTableFilters()
{
TableFilters.AddRange(new List<IFilterType<Table>>
{
new PeriodFilter(), // Keep this first as EF does not allow tables to contain a period character
// To include all the customer tables, but not the customer billing tables
//new RegexExcludeFilter(".*[Bb]illing.*"), // This excludes all tables with 'billing' anywhere in the name
//new RegexIncludeFilter("^[Cc]ustomer.*"), // This includes any remaining tables with names beginning with 'customer'
// To exclude all tables that contain '_FR_' or begin with 'data_'
//new RegexExcludeFilter("(.*_FR_.*)|(^data_.*)"),
// Pass in your own custom Regex
//new RegexIncludeFilter(new Regex("^tableName1$|^tableName2$", RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(200))),
// Add your own code to these custom filter classes
new TableFilter(),
new HasNameFilter(FilterType.Table),
});
}
public static void AddDefaultColumnFilters()
{
ColumnFilters.AddRange(new List<IFilterType<Column>>
{
// Exclude any columns that begin with 'FK_'
//new RegexExcludeFilter("^FK_.*$"),
// Add your own code to these custom filter classes
new ColumnFilter(),
new HasNameFilter(FilterType.Column),
});
}
public static void AddDefaultStoredProcedureFilters()
{
StoredProcedureFilters.AddRange(new List<IFilterType<StoredProcedure>>
{
new PeriodFilter(), // Keep this first as EF does not allow stored procedures to contain a period character
// Add your own code to these custom filter classes
new StoredProcedureFilter(),
new HasNameFilter(FilterType.StoredProcedure)
});
}
}
/// <summary>
/// Filtering can now be done via one or more Regex's and one or more functions.
/// Gone are the days of a single do-it-all regex, you can now split them up into many smaller Regex's.
/// It's now up to you how to want to mix and match them.
/// </summary>
public class SingleContextFilter : DbContextFilter
{
protected readonly List<IFilterType<Schema>> SchemaFilters;
protected readonly List<IFilterType<Table>> TableFilters;
protected readonly List<IFilterType<Column>> ColumnFilters;
protected readonly List<IFilterType<StoredProcedure>> StoredProcedureFilters;
private bool _hasMergedIncludeFilters;
public SingleContextFilter()
{
IncludeViews = FilterSettings.IncludeViews;
IncludeSynonyms = FilterSettings.IncludeSynonyms;
IncludeTableValuedFunctions = FilterSettings.IncludeTableValuedFunctions;
IncludeScalarValuedFunctions = FilterSettings.IncludeScalarValuedFunctions;
IncludeStoredProcedures = IncludeScalarValuedFunctions || IncludeTableValuedFunctions || FilterSettings.IncludeStoredProcedures;
SchemaFilters = FilterSettings.SchemaFilters;
TableFilters = FilterSettings.TableFilters;
ColumnFilters = FilterSettings.ColumnFilters;
StoredProcedureFilters = FilterSettings.StoredProcedureFilters;
_hasMergedIncludeFilters = false;
EnumDefinitions = new List<EnumDefinition>();
Settings.AddEnumDefinitions?.Invoke(EnumDefinitions);
}
public override bool IsExcluded(EntityName item)
{
if(!_hasMergedIncludeFilters)
{
MergeIncludeFilters();
_hasMergedIncludeFilters = true;
}
var schema = item as Schema;
if (schema != null)
return SchemaFilters.Any(filter => filter.IsExcluded(schema));
var table = item as Table;
if (table != null)
return TableFilters.Any(filter => filter.IsExcluded(table)) || SchemaFilters.Any(filter => filter.IsExcluded(table.Schema));
var column = item as Column;
if (column != null)
return ColumnFilters.Any(filter => filter.IsExcluded(column));
var sp = item as StoredProcedure;
if (sp != null)
return StoredProcedureFilters.Any(filter => filter.IsExcluded(sp)) || SchemaFilters.Any(filter => filter.IsExcluded(sp.Schema));
return false;
}
public override string TableRename(string name, string schema, bool isView)
{
// Callback to Settings, which can be set within <database>.tt
if (Settings.TableRename != null)
return Settings.TableRename(name, schema, isView);
return name;
}
public override string MappingTableRename(string mappingTable, string tableName, string entityName)
{
// Callback to Settings, which can be set within <database>.tt
if (Settings.MappingTableRename != null)
return Settings.MappingTableRename(mappingTable, tableName, entityName);
return entityName;
}
public List<EnumDefinition> EnumDefinitions;
public override void UpdateTable(Table table)
{
// Callback to Settings, which can be set within <database>.tt
Settings.UpdateTable?.Invoke(table);
}
public override void UpdateColumn(Column column, Table table)
{
// Callback to Settings, which can be set within <database>.tt
Settings.UpdateColumn?.Invoke(column, table, EnumDefinitions);
}
public override void ViewProcessing(Table view)
{
// Callback to Settings, which can be set within <database>.tt
Settings.ViewProcessing?.Invoke(view);
}
public override string StoredProcedureRename(StoredProcedure sp)
{
// Callback to Settings, which can be set within <database>.tt
if (Settings.StoredProcedureRename != null)
return Settings.StoredProcedureRename(sp);
return sp.NameHumanCase; // Do nothing by default
}
public override string StoredProcedureReturnModelRename(string name, StoredProcedure sp)
{
// Callback to Settings, which can be set within <database>.tt
if (Settings.StoredProcedureReturnModelRename != null)
return Settings.StoredProcedureReturnModelRename(name, sp);
return name; // Do nothing by default
}
public override ForeignKey ForeignKeyFilter(ForeignKey fk)
{
// Return null to exclude this foreign key, or set IncludeReverseNavigation = false
// to include the foreign key but not generate reverse navigation properties.
// Example, to exclude all foreign keys for the Categories table, use:
//if (fk.PkTableName == "Categories")
// return null;
// Example, to exclude reverse navigation properties for tables ending with Type, use:
//if (fk.PkTableName.EndsWith("Type"))
// fk.IncludeReverseNavigation = false;
// You can also change the access modifier of the foreign-key's navigation property:
//if(fk.PkTableName == "Categories")
// fk.AccessModifier = "internal";
return fk;
}
public override string[] ForeignKeyAnnotationsProcessing(Table fkTable, Table pkTable, string propName, string fkPropName)
{
// Callback to Settings, which can be set within <database>.tt
if (Settings.ForeignKeyAnnotationsProcessing != null)
return Settings.ForeignKeyAnnotationsProcessing(fkTable, pkTable, propName, fkPropName);
return null;
}
private void MergeIncludeFilters()
{
MergeIncludeFilters(SchemaFilters);
MergeIncludeFilters(TableFilters);
MergeIncludeFilters(ColumnFilters);
MergeIncludeFilters(StoredProcedureFilters);
}
private static void MergeIncludeFilters<T>(List<IFilterType<T>> filters)
{
var list = filters
.Where(x => x.GetType() == typeof(RegexIncludeFilter))
.Select(x => (RegexIncludeFilter) x)
.ToList();
if (list.Count < 2)
return; // Nothing to merge
var singleRegex = string.Join("|", list.Select(x => x.Pattern()));
filters.RemoveAll(filter => filter.GetType() == typeof(RegexIncludeFilter));
var singleIncludeFilter = (IFilterType<T>) new RegexIncludeFilter(singleRegex);
filters.Add(singleIncludeFilter);
}
}
// ****************************************************************************************************************************************
// **************************** No more settings to adjust. Rest of the generator code below. *********************************************
// ****************************************************************************************************************************************
public static class AssemblyHelper
{
public static object LoadPlugin(string assemblyAndType)
{
var assemblyInfo = assemblyAndType.Split(',');
return LoadPlugin(assemblyInfo[0], assemblyInfo[1]);
}
/// <summary>
/// Load a plugin
/// </summary>
/// <param name="assemblyFile">Full path including DLL name. i.e. "C:\\S\\Source (open source)\\EntityFramework Reverse POCO Code Generator\\Generator.Tests.Unit\\\bin\\Debug\\Generator.Tests.Unit.dll"</param>
/// <param name="typeName">Fully qualified class name, including any namespaces. i.e. "Generator.Tests.Unit.MultiContextSettingsPlugin"</param>
/// <returns></returns>
public static object LoadPlugin(string assemblyFile, string typeName)
{
var asm = Assembly.LoadFrom(assemblyFile.Trim());
var dynType = asm.GetType(typeName.Trim(), true, false);
return Activator.CreateInstance(dynType);
}
}
public class Column : EntityName
{
public string DisplayName; // Name used in the data annotation [Display(Name = "<DisplayName> goes here")]
public bool OverrideModifier = false; // Adds 'override' to the property declaration
public List<string> Attributes = new List<string>(); // List of attributes to add to this columns poco property
public bool Hidden; // If true, does not generate any code for this column.
public bool ExistsInBaseClass; // If true, does not generate the property for this column as it will exist in a base class
public int Scale;
public string PropertyType;
public string SqlPropertyType;
public int DateTimePrecision;
public string Default;
public int MaxLength;
public int Precision;
public int Ordinal;
public int PrimaryKeyOrdinal;
public string ExtendedProperty;
public string SummaryComments;
public string InlineComments;
public string UniqueIndexName;
public bool AllowEmptyStrings = true;
public bool IsIdentity;
public bool IsRowGuid;
public bool IsComputed;
public ColumnGeneratedAlwaysType GeneratedAlwaysType;
public bool IsNullable;
public bool IsPrimaryKey;
public bool IsUniqueConstraint;
public bool IsUnique;
public bool IsStoreGenerated;
public bool IsRowVersion;
public bool IsConcurrencyToken; // Manually set via callback
public bool IsFixedLength;
public bool IsUnicode;
public bool IsMaxLength;
public bool IsForeignKey;
public bool IsSpatial;
public string Config;
public List<string> ConfigFk = new List<string>();
//public string Entity;
public List<PropertyAndComments> EntityFk = new List<PropertyAndComments>();
public List<RawIndex> Indexes = new List<RawIndex>();
public Table ParentTable;
public static readonly List<string> NotNullable = new List<string>
{
Settings.AllowNullStrings ? "" : "string",
"byte[]",
"datatable",
"system.data.datatable",
"object",
"microsoft.sqlserver.types.sqlgeography",
"microsoft.sqlserver.types.sqlgeometry",
"sqlgeography",
"sqlgeometry",
"system.data.entity.spatial.dbgeography",
"system.data.entity.spatial.dbgeometry",
"dbgeography",
"dbgeometry",
"system.data.entity.hierarchy.hierarchyid",
"hierarchyid",
"nettopologysuite.geometries.point",
"nettopologysuite.geometries.geometry"
};
public static readonly List<string> StoredProcedureNotNullable = new List<string>
{
"string",
"byte[]",
"datatable",
"system.data.datatable",
"object",
"microsoft.sqlserver.types.sqlgeography",
"microsoft.sqlserver.types.sqlgeometry",
"sqlgeography",
"sqlgeometry",
"system.data.entity.spatial.dbgeography",
"system.data.entity.spatial.dbgeometry",
"dbgeography",
"dbgeometry",
"system.data.entity.hierarchy.hierarchyid",
"hierarchyid",
"nettopologysuite.geometries.point",
"nettopologysuite.geometries.geometry"
};
public static readonly List<string> CanUseSqlServerIdentityColumn = new List<string>