-
Notifications
You must be signed in to change notification settings - Fork 1
/
VsNorthwind.tt
589 lines (501 loc) · 37.1 KB
/
VsNorthwind.tt
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
<#@ include file="EF.Reverse.POCO.VS.ttinclude" #>
<#
// v3.1.3
// Please make changes to the settings below.
// All you have to do is save this file, and the output file(s) are generated. Compiling does not regenerate the file(s).
// A course for the older v2 generator is available on Pluralsight at https://www.pluralsight.com/courses/code-first-entity-framework-legacy-databases
// Settings ***************************************************************************************************************************
// Only the most popular settings are listed below.
// Either override Settings.* here, or edit the Settings, FilterSettings and SingleContextFilter classes located at the top of EF.Reverse.POCO.v3.ttinclude
// For help on the various Types below, please read https://github.com/sjh37/EntityFramework-Reverse-POCO-Code-First-Generator/wiki/Common-Settings.*Types-explained
// The following entries are the only required settings.
Settings.DatabaseType = DatabaseType.SqlServer; // SqlServer, SqlCe. Coming next: PostgreSQL, MySql, Oracle
Settings.TemplateType = TemplateType.EfCore3; // Ef6, EfCore2, EfCore3, FileBasedCore2, FileBasedCore3. FileBased specify folder using Settings.TemplateFolder
Settings.GeneratorType = GeneratorType.EfCore; // Ef6, EfCore, Custom. Custom edit GeneratorCustom class to provide your own implementation
Settings.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.
Settings.FileManagerType = FileManagerType.Custom; // .NET project = VisualStudio; .NET Core project = Custom; No output (testing only) = Null
Settings.ConnectionString = "Data Source=(local);Initial Catalog=Northwind;Integrated Security=True"; // This is used by the generator to reverse engineer your database
Settings.ConnectionStringName = "MyDbContext"; // ConnectionString key as specified in your app.config/web.config/appsettings.json. Not used by the generator, but is placed into the generated DbContext constructor.
Settings.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.
//Settings.DbContextInterfaceName= "IMyDbContext"; // Defaults to "I" + DbContextName or set string empty to not implement any interface.
Settings.GenerateSeparateFiles = false;
Settings.Namespace = "EfrpgVisualStudio"; // Override the default namespace here. Please use double quotes, example: "Accounts.Billing"
Settings.TemplateFolder = Path.Combine(Settings.Root, "Templates"); // 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
Settings.AddUnitTestingDbContext = true; // Will add a FakeDbContext and FakeDbSet for easy unit testing. Read https://github.com/sjh37/EntityFramework-Reverse-POCO-Code-First-Generator/wiki/FakeDbContext
// Elements to generate ***************************************************************************************************************
// Add the elements that should be generated when the template is executed.
// Multiple projects can be used that separate the different concerns.
Settings.ElementsToGenerate = Elements.Poco | Elements.Context | Elements.Interface | Elements.PocoConfiguration | Elements.Enum;
// Filtering **************************************************************************************************************************
// 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.
// You can have as many as you like, and mix and match them.
// These settings are only used by the single context filter SingleContextFilter (Settings.GenerateSingleDbContext = true)
// For further information please visit 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
// Single-context filtering is done via FilterSettings and SingleContextFilter classes.
// Override the filters here, or edit directly the FilterSettings and SingleContextFilter classes located at the top of EF.Reverse.POCO.v3.ttinclude
FilterSettings.Reset();
FilterSettings.AddDefaults();
// Examples:
//FilterSettings.IncludeViews = true;
//FilterSettings.IncludeSynonyms = false;
//FilterSettings.IncludeStoredProcedures = true;
//FilterSettings.IncludeTableValuedFunctions = false; // If true, for EF6 install the "EntityFramework.CodeFirstStoreFunctions" NuGet Package.
//FilterSettings.IncludeScalarValuedFunctions = false;
// Examples:
//FilterSettings.SchemaFilters.Add(new RegexExcludeFilter("[Ff]inance.*")); // This excludes the Finance schema
//FilterSettings.SchemaFilters.Add(new RegexIncludeFilter("dbo.*")); // This includes only dbo schema
//FilterSettings.TableFilters.Add(new RegexExcludeFilter(".*[Bb]illing.*")); // This excludes all tables with 'billing' anywhere in the name
//FilterSettings.TableFilters.Add(new RegexIncludeFilter("^[Cc]ustomer.*")); // This includes any remaining tables with names beginning with 'customer'
FilterSettings.TableFilters.Add(new RegexExcludeFilter("AspNet.*")); // This excludes all tables starting with 'AspNet'
FilterSettings.TableFilters.Add(new RegexExcludeFilter("__EFMigrationsHistory")); // This excludes all tables starting with 'AspNet'
//FilterSettings.ColumnFilters.Add(new RegexExcludeFilter("[Cc]reated[Aa]t.*")); // This excludes all columns starting with 'CreatedAt' e.g CreatedAtUtc
//FilterSettings.ColumnFilters.Add(new RegexIncludeFilter(".*")); // Rarely used as it would only include columns with names listed here
//FilterSettings.StoredProcedureFilters.Add(new RegexExcludeFilter("Calc")); // This excludes all stored procedures 'Calc' in the name
//FilterSettings.StoredProcedureFilters.Add(new RegexIncludeFilter("Pricing.*")); // This includes all stored procedures starting with 'Pricing'
// Other settings *********************************************************************************************************************
Settings.CommandTimeout = 600; // SQL Command timeout in seconds. 600 is 10 minutes, 0 will wait indefinitely. Some databases can be slow retrieving schema information.
Settings.DbContextInterfaceBaseClasses = "IDisposable"; // Specify what the base classes are for your database context interface
Settings.DbContextBaseClass = "DbContext"; // Specify what the base class is for your DbContext. For ASP.NET Identity use "IdentityDbContext<ApplicationUser>";
Settings.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
Settings.AddParameterlessConstructorToDbContext = true; // EF6 only. 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.
Settings.ConfigurationClassName = "Configuration"; // Configuration, Mapping, Map, etc. This is appended to the Poco class name to configure the mappings.
Settings.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.
Settings.EntityClassesModifiers = "public"; // "public partial";
Settings.ConfigurationClassesModifiers = "public"; // "public partial";
Settings.DbContextClassModifiers = "public"; // "public partial";
Settings.DbContextInterfaceModifiers = "public"; // "public partial";
Settings.ResultClassModifiers = "public"; // "public partial";
Settings.UsePascalCase = true; // This will rename the generated C# tables & properties to use PascalCase. If false table & property names will be left alone.
Settings.UseDataAnnotations = false; // If true, will add data annotations to the poco classes.
Settings.UsePropertyInitialisers = false; // Removes POCO constructor and instead uses C# 6 property initialisers to set defaults
Settings.UseLazyLoading = true; // Marks all navigation properties as virtual or not, to support or disable EF Lazy Loading feature
Settings.UseInheritedBaseInterfaceFunctions = false; // If true, the main DBContext interface functions will come from the DBContextInterfaceBaseClasses and not generated. If false, the functions will be generated.
Settings.IncludeComments = CommentsStyle.AtEndOfField; // Adds comments to the generated code
Settings.IncludeExtendedPropertyComments = CommentsStyle.InSummaryBlock; // Adds extended properties as comments to the generated code
Settings.IncludeConnectionSettingComments = true; // Add comments describing connection settings used to generate file
Settings.DisableGeographyTypes = true; // Turns off use of spatial types: Geography, Geometry. More info: https://github.com/sjh37/EntityFramework-Reverse-POCO-Code-First-Generator/wiki/Spatial-Types
Settings.CollectionInterfaceType = "ICollection"; // = "System.Collections.Generic.List"; // Determines the declaration type of collections for the Navigation Properties. ICollection is used if not set.
Settings.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".
Settings.NullableShortHand = true; // true => T?, false => Nullable<T>
Settings.AddIDbContextFactory = true; // Will add a default IDbContextFactory<DbContextName> implementation for easy dependency injection
Settings.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).
Settings.IncludeCodeGeneratedAttribute = false; // If true, will include the GeneratedCode attribute, false to remove it.
Settings.UsePrivateSetterForComputedColumns = true; // If the columns is computed, use a private setter.
Settings.AdditionalNamespaces = new List<string>(); // To include extra namespaces, include them here. i.e. new List<string> { "Microsoft.AspNetCore.Identity.EntityFrameworkCore", "System.ComponentModel.DataAnnotations" };
Settings.AdditionalContextInterfaceItems = new List<string>(); // example: new List<string> { "void SetAutoDetectChangesEnabled(bool flag);" };
// Language choices
Settings.GenerationLanguage = GenerationLanguage.CSharp;
Settings.FileExtension = ".cs";
// Code suppression (useful for non C# file generation) *******************************************************************************
Settings.UseRegions = true; // If false, suppresses the use of #region
Settings.UseNamespace = true; // If false, suppresses the writing of a namespace
Settings.UsePragma = true; // If false, suppresses the writing of #pragma
// Enumerations ***********************************************************************************************************************
// Create enumerations from database tables
// List the enumeration tables you want read and generated for
Settings.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
// }
};
// 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.
Settings.AddEnumDefinitions = delegate(List<EnumDefinition> enumDefinitions)
{
// Examples:
//enumDefinitions.Add(new EnumDefinition { Schema = "dbo", 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 = "dbo", Table = "OrderHeader", Column = "OrderStatus", EnumType = "OrderStatusType" });
// This will replace any table *.OrderStatus type to be an OrderStatusType enum
//enumDefinitions.Add(new EnumDefinition { Schema = "dbo", Table = "*", Column = "OrderStatus", EnumType = "OrderStatusType" });
};
// 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
// Settings.StoredProcedureReturnTypes.Add("SalesByYear", "SummaryOfSalesByYear");
// Additional attributes on on reverse navigation and foreign key properties **********************************************************
// 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
Settings.AdditionalReverseNavigationsDataAnnotations = new string[]
{
// "JsonIgnore" // Also add "Newtonsoft.Json" to the AdditionalNamespaces array above
};
Settings.AdditionalForeignKeysDataAnnotations = new string[]
{
// "JsonIgnore" // Also add "Newtonsoft.Json" to the AdditionalNamespaces array above
};
// Reference other namespaces *********************************************************************************************************
// 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:
Settings.PocoNamespace = ""; // "YourProject.Entities";
Settings.ContextNamespace = ""; // "YourProject.Context";
Settings.InterfaceNamespace = ""; // "YourProject.Context";
Settings.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.
Settings.PrependSchemaName = true; // Control if the schema name is prepended to the table name
// 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
Settings.TableSuffix = null;
// Call-backs *************************************************************************************************************************
// AddRelationship is a helper function that creates ForeignKey objects and adds them to the foreignKeys list
Settings.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", "dbo", "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", "dbo", "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", "dbo", "Order Details", new[] { "OrderID", "ProductID" }, "dbo", "Invoices", new[] { "OrderID", "ProductID" }, null, null, true);
};
// Table renaming (single context generation only) ************************************************************************************
// Use the following function to rename tables such as tblOrders to Orders, Shipments_AB to Shipments, etc.
// Example:
Settings.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
Settings.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>";
// 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.
Settings.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("SomeTable", StringComparison.InvariantCultureIgnoreCase))
// column.Hidden = true;
// Use the extended properties to perform tasks to column
//if (column.ExtendedProperty == "HIDE")
// column.Hidden = true;
// 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; }
if(Settings.UseDataAnnotations)
{
if (column.IsPrimaryKey)
column.Attributes.Add("[Key]");
if (column.IsMaxLength)
column.Attributes.Add("[MaxLength]");
if (column.IsRowVersion)
column.Attributes.Add("[Timestamp]");
if (!column.IsMaxLength && column.MaxLength > 0)
{
var doNotSpecifySize = (Settings.DatabaseType == DatabaseType.SqlCe && column.MaxLength > 4000);
column.Attributes.Add(doNotSpecifySize ? "[MaxLength]" : string.Format("[MaxLength({0})]", column.MaxLength));
if (column.PropertyType.Equals("string", StringComparison.InvariantCultureIgnoreCase))
column.Attributes.Add(string.Format("[StringLength({0})]", column.MaxLength));
}
if (!column.IsNullable && !column.IsComputed)
{
if (column.PropertyType.Equals("string", StringComparison.InvariantCultureIgnoreCase) && column.AllowEmptyStrings)
column.Attributes.Add("[Required(AllowEmptyStrings = true)]");
else
column.Attributes.Add("[Required]");
}
column.Attributes.Add(string.Format("[Display(Name = \"{0}\")]", column.DisplayName));
}
// 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.
Settings.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.
Settings.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.
Settings.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:
Settings.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;
};
Settings.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
Settings.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;
};
Settings.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;
};
// 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
Settings.GenerateSingleDbContext = true; // Set this to false to generate multiple db contexts.
Settings.MultiContextSettingsConnectionString = ""; // Leave empty to read data from same database in ConnectionString above. If settings are in another database, specify the connection string here.
Settings.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.
Settings.MultiContextAttributeDelimiter = '~'; // The delimiter used for splitting MultiContext attributes
Settings.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());
}*/
};
Settings.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());
}*/
};
Settings.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();
}*/
};
Settings.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();
}*/
};
// Don't forget to take a look at SingleContextFilter and FilterSettings classes!
// That's it, nothing else to configure ***********************************************************************************************
FilterSettings.CheckSettings();
Inflector.PluralisationService = new EnglishPluralizationService(); // To disable pluralisation, set this to null
var outer = (GeneratedTextTransformation) this;
var fileManagement = new FileManagementService(outer);
var generator = GeneratorFactory.Create(fileManagement, FileManagerFactory.GetFileManagerType());
if (generator.InitialisationOk)
{
generator.ReadDatabase();
generator.GenerateCode();
}
fileManagement.Process(true);#>