<#@ include file="EF.Reverse.POCO.Core.ttinclude" #>
<#
// v2.18.1
// Please make changes to the settings below.
// All you have to do is save this file, and the output file(s) is/are generated. Compiling does not regenerate the file(s). // Main settings **********************************************************************************************************************
// Namespace = ""; // Override the default namespace here
DbContextName = "MyDbContext";
DbContextInterfaceBaseClasses = "System.IDisposable"; // Specify what the base classes are for your database context interface
DbContextBaseClass = "System.Data.Entity.DbContext"; // Specify what the base class is for your DbContext. For ASP.NET Identity use "IdentityDbContext<ApplicationUser>"
ConnectionStringName = "MyDbContext"; // Searches for this connection string in config files listed below
TargetFrameworkVersion = "4.51"; // Please set this to your .NET framework version, 4.0, 4.5, 4.51, etc.
ConfigurationClassName = "Configuration"; // Configuration, Mapping, Map, etc. This is appended to the Poco class name to configure the mappings.
ConfigFilenameSearchOrder = new[] { "app.config", "web.config", "app.config.transform", "web.config.transform" }; // Add more here if required. The config files are searched for in the local project first, then the whole solution second.
MakeClassesPartial = false;
GenerateSeparateFiles = false;
UseCamelCase = true; // This will rename the tables & fields to use CamelCase. If false table & field names will be left alone.
IncludeComments = true; // Adds comments to the generated code
IncludeExtendedPropertyComments = ExtendedPropertyCommentsStyle.InSummaryBlock; // Adds extended properties as comments to the generated code
IncludeViews = true;
IncludeStoredProcedures = true;
IncludeTableValuedFunctions = false; // If true, you must also install the "EntityFramework.CodeFirstStoreFunctions" Nuget Package.
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.
CollectionType = "System.Collections.Generic.List"; // Determines the type of collection for the Navigation Properties. "ObservableCollection" for example. Add "System.Collections.ObjectModel" to AdditionalNamespaces if setting the CollectionType = "ObservableCollection".
AddUnitTestingDbContext = true; // Will add a FakeDbContext and FakeDbSet for easy unit testing
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).
AdditionalNamespaces = new[] { "" }; // To include extra namespaces, include them here. i.e. "Microsoft.AspNet.Identity.EntityFramework"
AdditionalContextInterfaceItems = new[] // To include extra db context interface items, include them here. Also set MakeClassesPartial=true, and implement the partial DbContext class functions.
{
"" // example: "void SetAutoDetectChangesEnabled(bool flag);"
};
// If you need to serialize your entities with the JsonSerializer from Newtonsoft, this would serialize
// 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.
AdditionalReverseNavigationsDataAnnotations = new string[] // Data Annotations for ReverseNavigationProperty.
{
// "JsonIgnore"
};
AdditionalForeignKeysDataAnnotations = new string[] // Data Annotations for ForeignKeys.
{
// "JsonIgnore"
}; // Migrations *************************************************************************************************************************
MigrationConfigurationFileName = ""; // null or empty to not create migrations
MigrationStrategy = "MigrateDatabaseToLatestVersion"; // MigrateDatabaseToLatestVersion, CreateDatabaseIfNotExists or DropCreateDatabaseIfModelChanges
ContextKey = ""; // Sets the string used to distinguish migrations belonging to this configuration from migrations belonging to other configurations using the same database. This property enables migrations from multiple different models to be applied to applied to a single database.
AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = true; // if true, can drop fields and lose data during automatic migration // Pluralization **********************************************************************************************************************
// To turn off pluralization, use:
// Inflector.PluralizationService = null;
// Default pluralization, use:
// Inflector.PluralizationService = new EnglishPluralizationService();
// For Spanish pluralization:
// 1. Intall the "EF6.Contrib" Nuget Package.
// 2. Add the following to the top of this file and adjust path, and remove the space between the angle bracket and # at the beginning and end.
// < #@ assembly name="your full path to \EntityFramework.Contrib.dll" # >
// 3. Change the line below to: Inflector.PluralizationService = new SpanishPluralizationService();
Inflector.PluralizationService = new EnglishPluralizationService(new[]
{
// Create custom ("Singular", "Plural") forms for one-off words as needed
new CustomPluralizationEntry("LiveQuiz", "LiveQuizzes"),
new CustomPluralizationEntry("Course", "Courses"),
new CustomPluralizationEntry("CustomerStatus", "CustomerStatus"), // Use same value to prevent pluralisation
new CustomPluralizationEntry("EmployeeStatus", "EmployeeStatus")
}); // 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.
ElementsToGenerate = Elements.Poco | Elements.Context | Elements.UnitOfWork | Elements.PocoConfiguration; // Use these namespaces to specify where the different elements now live. These may even be in different assemblies.
// Please note this does not create the files in these locations, it only adds a using statement to say where they are.
// I show how this works on the video from 26:08 onwards.
// 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.UnitOfWork; in your Context folder,
// ElementsToGenerate = Elements.PocoConfiguration; in your Maps folder.
// PocoNamespace = "YourProject.Entities";
// ContextNamespace = "YourProject.Context";
// UnitOfWorkNamespace = "YourProject.Context";
// PocoConfigurationNamespace = "YourProject.Maps";
// You also need to set the following to the namespace where they now live:
PocoNamespace = "";
ContextNamespace = "";
UnitOfWorkNamespace = "";
PocoConfigurationNamespace = ""; // 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.
PrependSchemaName = true; // Control if the schema name is prepended to the table name // Filtering **************************************************************************************************************************
// Use the following table/view name regex filters to include or exclude tables/views
// Exclude filters are checked first and tables matching filters are removed.
// * If left null, none are excluded.
// * If not null, any tables matching the regex are excluded.
// Include filters are checked second.
// * If left null, all are included.
// * If not null, only the tables matching the regex are included.
// Example: TableFilterExclude = new Regex(".*auto.*");
// TableFilterInclude = new Regex("(.*_FR_.*)|(data_.*)");
// TableFilterInclude = new Regex("^table_name1$|^table_name2$|etc");
// ColumnFilterExclude = new Regex("^FK_.*$");
SchemaFilterExclude = null;
SchemaFilterInclude = null;
TableFilterExclude = null;
TableFilterInclude = null;
ColumnFilterExclude = null; // Stored Procedures ******************************************************************************************************************
// Use the following regex filters to include or exclude stored procedures
StoredProcedureFilterExclude = null;
StoredProcedureFilterInclude = null; // Table renaming *********************************************************************************************************************
// Use the following function to rename tables such as tblOrders to Orders, Shipments_AB to Shipments, etc.
// Example:
/*TableRename = (name, schema) =>
{
if (name.StartsWith("tbl"))
name = name.Remove(0, 3);
return name.Replace("_AB", "");
};*/
TableRename = (name, schema) => name; // Do nothing by default // 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.
//EnumsDefinitions.Add(new EnumDefinition { Schema = "dbo", Table = "match_table_name", Column = "match_column_name", EnumType = "name_of_enum" });
//EnumsDefinitions.Add(new EnumDefinition { Schema = "dbo", Table = "OrderHeader", Column = "OrderStatus", EnumType = "OrderStatusType" }); // This will replace OrderHeader.OrderStatus type to be an OrderStatusType enum // Use the following function if you need to apply additional modifications to a column
// eg. normalise names etc.
UpdateColumn = (Column column, Table table) =>
{
// Example
//if (column.NameHumanCase == "PkId")
// column.NameHumanCase = "Id"; // Perform Enum property type replacement
var enumDefinition = EnumsDefinitions.FirstOrDefault(e =>
(e.Schema.ToLowerInvariant() == table.Schema.ToLowerInvariant()) &&
(e.Table == table.Name || e.Table == table.NameHumanCase) &&
(e.Column == column.Name || e.Column == column.NameHumanCase)); if (enumDefinition != null)
column.PropertyType = enumDefinition.EnumType; return column;
}; // StoredProcedure renaming ************************************************************************************************************
// Use the following function to rename stored procs such as sp_CreateOrderHistory to CreateOrderHistory, my_sp_shipments to Shipments, etc.
// Example:
/*StoredProcedureRename = (name, schema) =>
{
if (name.StartsWith("sp_"))
name = name.Remove(0, 3);
return name.Replace("my_sp_", "");
};*/
StoredProcedureRename = (name, schema) => name; // Do nothing by default // 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"); // WCF ********************************************************************************************************************************
// This is only intended as a helper, to get you started creating WCF contracts, and to save a lot of typing.
AddWcfDataAttributes = false;
ExtraWcfDataContractAttributes = ""; // This string is inserted into the [DataContract] attribute, before the closing square bracket.
// Example: ""; = [DataContract]
// "(Namespace = \"http://www.contoso.com\")"; = [DataContract(Namespace = "http://www.contoso.com")]
// "(Namespace = Constants.ServiceNamespace)"; = [DataContract(Namespace = Constants.ServiceNamespace)] // Callbacks **********************************************************************************************************************
// This method will be called right before we write the POCO header.
Action<Table> WritePocoClassAttributes = t =>
{
// Do nothing by default
// Example:
// if(t.ClassName.StartsWith("Order"))
// WriteLine(" [SomeAttribute]");
}; // Writes optional base classes
Func<Table, string> WritePocoBaseClasses = t =>
{
//if (t.ClassName == "User")
// return ": IdentityUser<int, CustomUserLogin, CustomUserRole, CustomUserClaim>";
return "";
}; // Writes any boilerplate stuff
Action<Table> WritePocoBaseClassBody = t =>
{
// Do nothing by default
// Example:
// WriteLine(" // " + t.ClassName);
}; Func<Column, string> WritePocoColumn = c => c.Entity; Func<StoredProcedure, string> WriteStoredProcFunctionName = sp => sp.NameHumanCase; Func<StoredProcedure, bool, string> WriteStoredProcFunctionParams = (sp, includeProcResult) =>
{
var sb = new StringBuilder();
int n = 1;
int count = sp.Parameters.Count;
foreach (var p in sp.Parameters.OrderBy(x => x.Ordinal))
{
sb.AppendFormat("{0}{1}{2} {3}{4}",
p.Mode == StoredProcedureParameterMode.In ? "" : "out ",
p.PropertyType,
NotNullable.Contains(p.PropertyType.ToLower()) ? string.Empty : "?",
p.NameHumanCase,
(n++ < count) ? ", " : string.Empty);
}
if (includeProcResult && sp.ReturnModels.Count > 0 && sp.ReturnModels.First().Count > 0)
sb.AppendFormat((sp.Parameters.Count > 0 ? ", " : "") + "out int procResult");
return sb.ToString();
}; Func<StoredProcedure, string> WriteStoredProcFunctionOverloadCall = (sp) =>
{
var sb = new StringBuilder();
foreach (var p in sp.Parameters.OrderBy(x => x.Ordinal))
{
sb.AppendFormat("{0}{1}, ",
p.Mode == StoredProcedureParameterMode.In ? "" : "out ",
p.NameHumanCase);
}
sb.Append("out procResult");
return sb.ToString();
}; Func<StoredProcedure, string> WriteStoredProcFunctionSqlAtParams = sp =>
{
var sb = new StringBuilder();
int n = 1;
int count = sp.Parameters.Count;
foreach (var p in sp.Parameters.OrderBy(x => x.Ordinal))
{
sb.AppendFormat("{0}{1}{2}",
p.Name,
p.Mode == StoredProcedureParameterMode.In ? string.Empty : " OUTPUT",
(n++ < count) ? ", " : string.Empty);
}
return sb.ToString();
}; Func<StoredProcedureParameter, string> WriteStoredProcSqlParameterName = p => p.NameHumanCase + "Param"; Func<StoredProcedure, string> WriteStoredProcFunctionDeclareSqlParameter = sp =>
{
var sb = new StringBuilder();
foreach (var p in sp.Parameters.OrderBy(x => x.Ordinal))
{
bool isNullable = !NotNullable.Contains(p.PropertyType.ToLower());
var getValueOrDefault = isNullable ? ".GetValueOrDefault()" : string.Empty; sb.AppendLine(string.Format(" var {0} = new System.Data.SqlClient.SqlParameter {{ ParameterName = \"{1}\", SqlDbType = System.Data.SqlDbType.{2}, Direction = System.Data.ParameterDirection.{3}{4}{5}{6}{7} }};",
WriteStoredProcSqlParameterName(p),
p.Name,
p.SqlDbType,
p.Mode == StoredProcedureParameterMode.In ? "Input" : "Output",
p.Mode == StoredProcedureParameterMode.In ? ", Value = " + p.NameHumanCase + getValueOrDefault : string.Empty,
p.MaxLength > 0 ? ", Size = " + p.MaxLength : string.Empty,
(p.Precision > 0 || p.Scale > 0) ? ", Precision = " + p.Precision + ", Scale = " + p.Scale : string.Empty,
p.PropertyType.ToLower().Contains("datatable") ? ", TypeName = \"" + p.UserDefinedTypeName + "\"" : string.Empty)); if (p.Mode == StoredProcedureParameterMode.In)
{
sb.AppendFormat(
isNullable
? " if (!{0}.HasValue){1} {0}Param.Value = System.DBNull.Value;{1}{1}"
: " if ({0}Param.Value == null){1} {0}Param.Value = System.DBNull.Value;{1}{1}",
p.NameHumanCase, Environment.NewLine);
}
}
if(sp.ReturnModels.Count < 2)
sb.AppendLine(" var procResultParam = new System.Data.SqlClient.SqlParameter { ParameterName = \"@procResult\", SqlDbType = System.Data.SqlDbType.Int, Direction = System.Data.ParameterDirection.Output };");
return sb.ToString();
}; Func<StoredProcedure, string> WriteTableValuedFunctionDeclareSqlParameter = sp =>
{
var sb = new StringBuilder();
foreach (var p in sp.Parameters.OrderBy(x => x.Ordinal))
{
var getValueOrDefault = NotNullable.Contains(p.PropertyType.ToLower()) ? string.Empty : ".GetValueOrDefault()"; sb.AppendLine(string.Format(" var {0}Param = new System.Data.Entity.Core.Objects.ObjectParameter(\"{1}\", {2});",
p.NameHumanCase,
p.Name.Substring(1),
p.Mode == StoredProcedureParameterMode.In ? p.NameHumanCase + getValueOrDefault : string.Empty));
}
return sb.ToString();
}; Func<StoredProcedure, string> WriteStoredProcFunctionSqlParameterAnonymousArray = sp =>
{
var sb = new StringBuilder();
foreach (var p in sp.Parameters.OrderBy(x => x.Ordinal))
{
sb.Append(string.Format("{0}Param, ", p.NameHumanCase));
}
sb.Append("procResultParam");
return sb.ToString();
}; Func<StoredProcedure, string> WriteTableValuedFunctionSqlParameterAnonymousArray = sp =>
{
if (sp.Parameters.Count == 0)
return "new System.Data.Entity.Core.Objects.ObjectParameter[] { }";
var sb = new StringBuilder();
foreach (var p in sp.Parameters.OrderBy(x => x.Ordinal))
{
sb.Append(string.Format("{0}Param, ", p.NameHumanCase));
}
return sb.ToString().Substring(0, sb.Length - 2);
}; Func<StoredProcedure, bool, string> WriteStoredProcFunctionSetSqlParameters = (sp, isFake) =>
{
var sb = new StringBuilder();
foreach (var p in sp.Parameters.Where(x => x.Mode != StoredProcedureParameterMode.In).OrderBy(x => x.Ordinal))
{
string Default = string.Format("default({0})", p.PropertyType);
bool notNullable = NotNullable.Contains(p.PropertyType.ToLower()); if(isFake)
sb.AppendLine(string.Format(" {0} = {1};", p.NameHumanCase, Default));
else
{
sb.AppendLine(string.Format(" if (IsSqlParameterNull({0}Param))", p.NameHumanCase));
sb.AppendLine(string.Format(" {0} = {1};", p.NameHumanCase, notNullable ? Default : "null"));
sb.AppendLine(" else");
sb.AppendLine(string.Format(" {0} = ({1}) {2}Param.Value;", p.NameHumanCase, p.PropertyType, p.NameHumanCase));
}
}
return sb.ToString();
}; Func<StoredProcedure, string> WriteStoredProcReturnModelName = sp =>
StoredProcedureReturnTypes.ContainsKey(sp.NameHumanCase)
? StoredProcedureReturnTypes[sp.NameHumanCase]
: StoredProcedureReturnTypes.ContainsKey(sp.Name)
? StoredProcedureReturnTypes[sp.Name]
: string.Format("{0}ReturnModel", sp.NameHumanCase); Func<DataColumn, string> WriteStoredProcReturnColumn = col =>
string.Format("public System.{0}{1}{2} {{ get; set; }}",
col.DataType.Name, StoredProcedure.CheckNullable(col), col.ColumnName); Func<StoredProcedure, string> WriteStoredProcReturnType = (sp) =>
{
var returnModelCount = sp.ReturnModels.Count;
if (returnModelCount == 0)
return "int"; var spReturnClassName = WriteStoredProcReturnModelName(sp);
return (returnModelCount == 1) ? string.Format("System.Collections.Generic.List<{0}>", spReturnClassName) : spReturnClassName;
}; // That's it, nothing else to configure *********************************************************************************************** // Read schema
var factory = GetDbProviderFactory();
IsSqlCe = IsSqlCeConnection(factory);
var tables = LoadTables(factory);
var storedProcs = LoadStoredProcs(factory); // Generate output
if (tables.Count > 0 || storedProcs.Count > 0)
{
#>
<#@ include file="EF.Reverse.POCO.ttinclude" #>
<#@ import namespace="System.Xml.Schema" #>
<# } #>

<#@ include file="EF.Reverse.POCO.Core.ttinclude" #><#    // v2.18.1    // Please make changes to the settings below.    // All you have to do is save this file, and the output file(s) is/are generated. Compiling does not regenerate the file(s).
    // Main settings **********************************************************************************************************************    // Namespace = ""; // Override the default namespace here    DbContextName = "MyDbContext";    DbContextInterfaceBaseClasses = "System.IDisposable";    // Specify what the base classes are for your database context interface    DbContextBaseClass = "System.Data.Entity.DbContext";   // Specify what the base class is for your DbContext. For ASP.NET Identity use "IdentityDbContext<ApplicationUser>"    ConnectionStringName = "MyDbContext";   // Searches for this connection string in config files listed below    TargetFrameworkVersion = "4.51"; // Please set this to your .NET framework version, 4.0, 4.5, 4.51, etc.    ConfigurationClassName = "Configuration"; // Configuration, Mapping, Map, etc. This is appended to the Poco class name to configure the mappings.    ConfigFilenameSearchOrder = new[] { "app.config", "web.config", "app.config.transform", "web.config.transform" }; // Add more here if required. The config files are searched for in the local project first, then the whole solution second.    MakeClassesPartial = false;    GenerateSeparateFiles = false;    UseCamelCase = true;    // This will rename the tables & fields to use CamelCase. If false table & field names will be left alone.    IncludeComments = true; // Adds comments to the generated code    IncludeExtendedPropertyComments = ExtendedPropertyCommentsStyle.InSummaryBlock; // Adds extended properties as comments to the generated code    IncludeViews = true;    IncludeStoredProcedures = true;    IncludeTableValuedFunctions = false; // If true, you must also install the "EntityFramework.CodeFirstStoreFunctions" Nuget Package.    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.    CollectionType = "System.Collections.Generic.List";  // Determines the type of collection for the Navigation Properties. "ObservableCollection" for example. Add "System.Collections.ObjectModel" to AdditionalNamespaces if setting the CollectionType = "ObservableCollection".    AddUnitTestingDbContext = true; // Will add a FakeDbContext and FakeDbSet for easy unit testing    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).    AdditionalNamespaces = new[] { "" };  // To include extra namespaces, include them here. i.e. "Microsoft.AspNet.Identity.EntityFramework"    AdditionalContextInterfaceItems = new[] // To include extra db context interface items, include them here. Also set MakeClassesPartial=true, and implement the partial DbContext class functions.    {        ""  //  example: "void SetAutoDetectChangesEnabled(bool flag);"    };    // If you need to serialize your entities with the JsonSerializer from Newtonsoft, this would serialize    // 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.    AdditionalReverseNavigationsDataAnnotations = new string[] // Data Annotations for ReverseNavigationProperty.    {        // "JsonIgnore"    };      AdditionalForeignKeysDataAnnotations = new string[] // Data Annotations for ForeignKeys.    {        // "JsonIgnore"    };  
    // Migrations *************************************************************************************************************************    MigrationConfigurationFileName = ""; // null or empty to not create migrations    MigrationStrategy = "MigrateDatabaseToLatestVersion"; // MigrateDatabaseToLatestVersion, CreateDatabaseIfNotExists or DropCreateDatabaseIfModelChanges    ContextKey = ""; // Sets the string used to distinguish migrations belonging to this configuration from migrations belonging to other configurations using the same database. This property enables migrations from multiple different models to be applied to applied to a single database.    AutomaticMigrationsEnabled = true;    AutomaticMigrationDataLossAllowed = true; // if true, can drop fields and lose data during automatic migration
    // Pluralization **********************************************************************************************************************    // To turn off pluralization, use:    //      Inflector.PluralizationService = null;    // Default pluralization, use:    //      Inflector.PluralizationService = new EnglishPluralizationService();    // For Spanish pluralization:    //      1. Intall the "EF6.Contrib" Nuget Package.    //      2. Add the following to the top of this file and adjust path, and remove the space between the angle bracket and # at the beginning and end.    //         < #@ assembly name="your full path to \EntityFramework.Contrib.dll" # >    //      3. Change the line below to: Inflector.PluralizationService = new SpanishPluralizationService();    Inflector.PluralizationService = new EnglishPluralizationService(new[]    {        // Create custom ("Singular", "Plural") forms for one-off words as needed        new CustomPluralizationEntry("LiveQuiz", "LiveQuizzes"),        new CustomPluralizationEntry("Course", "Courses"),        new CustomPluralizationEntry("CustomerStatus", "CustomerStatus"), // Use same value to prevent pluralisation        new CustomPluralizationEntry("EmployeeStatus", "EmployeeStatus")    });            // 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.    ElementsToGenerate = Elements.Poco | Elements.Context | Elements.UnitOfWork | Elements.PocoConfiguration;
    // Use these namespaces to specify where the different elements now live. These may even be in different assemblies.    // Please note this does not create the files in these locations, it only adds a using statement to say where they are.    // I show how this works on the video from 26:08 onwards.    // 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.UnitOfWork; in your Context folder,    //      ElementsToGenerate = Elements.PocoConfiguration; in your Maps folder.    //      PocoNamespace = "YourProject.Entities";    //      ContextNamespace = "YourProject.Context";    //      UnitOfWorkNamespace = "YourProject.Context";    //      PocoConfigurationNamespace = "YourProject.Maps";    // You also need to set the following to the namespace where they now live:    PocoNamespace = "";    ContextNamespace = "";    UnitOfWorkNamespace = "";    PocoConfigurationNamespace = "";
        // 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.    PrependSchemaName = true;   // Control if the schema name is prepended to the table name

// Filtering **************************************************************************************************************************    // Use the following table/view name regex filters to include or exclude tables/views    // Exclude filters are checked first and tables matching filters are removed.    //  * If left null, none are excluded.    //  * If not null, any tables matching the regex are excluded.    // Include filters are checked second.    //  * If left null, all are included.    //  * If not null, only the tables matching the regex are included.    //  Example:    TableFilterExclude = new Regex(".*auto.*");    //              TableFilterInclude = new Regex("(.*_FR_.*)|(data_.*)");    //              TableFilterInclude = new Regex("^table_name1$|^table_name2$|etc");    //              ColumnFilterExclude = new Regex("^FK_.*$");    SchemaFilterExclude = null;    SchemaFilterInclude = null;    TableFilterExclude = null;    TableFilterInclude = null;    ColumnFilterExclude = null;
    // Stored Procedures ******************************************************************************************************************    // Use the following regex filters to include or exclude stored procedures    StoredProcedureFilterExclude = null;    StoredProcedureFilterInclude = null;

// Table renaming *********************************************************************************************************************    // Use the following function to rename tables such as tblOrders to Orders, Shipments_AB to Shipments, etc.    // Example:    /*TableRename = (name, schema) =>    {        if (name.StartsWith("tbl"))            name = name.Remove(0, 3);        return name.Replace("_AB", "");    };*/    TableRename = (name, schema) => name;   // Do nothing by default        // 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.    //EnumsDefinitions.Add(new EnumDefinition { Schema = "dbo", Table = "match_table_name", Column = "match_column_name", EnumType = "name_of_enum" });    //EnumsDefinitions.Add(new EnumDefinition { Schema = "dbo", Table = "OrderHeader", Column = "OrderStatus", EnumType = "OrderStatusType" }); // This will replace OrderHeader.OrderStatus type to be an OrderStatusType enum        // Use the following function if you need to apply additional modifications to a column    // eg. normalise names etc.    UpdateColumn = (Column column, Table table) =>     {        // Example        //if (column.NameHumanCase == "PkId")        //    column.NameHumanCase = "Id";
        // Perform Enum property type replacement        var enumDefinition = EnumsDefinitions.FirstOrDefault(e =>            (e.Schema.ToLowerInvariant() == table.Schema.ToLowerInvariant()) &&            (e.Table == table.Name || e.Table == table.NameHumanCase) &&            (e.Column == column.Name || e.Column == column.NameHumanCase));
        if (enumDefinition != null)            column.PropertyType = enumDefinition.EnumType;                return column;    };
    // StoredProcedure renaming ************************************************************************************************************    // Use the following function to rename stored procs such as sp_CreateOrderHistory to CreateOrderHistory, my_sp_shipments to Shipments, etc.    // Example:    /*StoredProcedureRename = (name, schema) =>    {        if (name.StartsWith("sp_"))            name = name.Remove(0, 3);        return name.Replace("my_sp_", "");    };*/    StoredProcedureRename = (name, schema) => name;   // Do nothing by default
    // 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");

// WCF ********************************************************************************************************************************    // This is only intended as a helper, to get you started creating WCF contracts, and to save a lot of typing.    AddWcfDataAttributes = false;    ExtraWcfDataContractAttributes = "";    // This string is inserted into the  [DataContract] attribute, before the closing square bracket.    // Example: "";                                           = [DataContract]    //          "(Namespace = \"http://www.contoso.com\")";   = [DataContract(Namespace = "http://www.contoso.com")]    //          "(Namespace = Constants.ServiceNamespace)";   = [DataContract(Namespace = Constants.ServiceNamespace)]    
    // Callbacks **********************************************************************************************************************    // This method will be called right before we write the POCO header.    Action<Table> WritePocoClassAttributes = t =>    {        // Do nothing by default        // Example:        // if(t.ClassName.StartsWith("Order"))        //     WriteLine("    [SomeAttribute]");    };
    // Writes optional base classes    Func<Table, string> WritePocoBaseClasses = t =>    {        //if (t.ClassName == "User")        //    return ": IdentityUser<int, CustomUserLogin, CustomUserRole, CustomUserClaim>";        return "";    };
    // Writes any boilerplate stuff    Action<Table> WritePocoBaseClassBody = t =>    {        // Do nothing by default        // Example:        // WriteLine("        // " + t.ClassName);    };
    Func<Column, string> WritePocoColumn = c => c.Entity;
    Func<StoredProcedure, string> WriteStoredProcFunctionName = sp => sp.NameHumanCase;
    Func<StoredProcedure, bool, string> WriteStoredProcFunctionParams = (sp, includeProcResult) =>    {        var sb = new StringBuilder();        int n = 1;        int count = sp.Parameters.Count;        foreach (var p in sp.Parameters.OrderBy(x => x.Ordinal))        {            sb.AppendFormat("{0}{1}{2} {3}{4}",                 p.Mode == StoredProcedureParameterMode.In ? "" : "out ",                 p.PropertyType,                NotNullable.Contains(p.PropertyType.ToLower()) ? string.Empty : "?",                p.NameHumanCase,                 (n++ < count) ? ", " : string.Empty);        }        if (includeProcResult && sp.ReturnModels.Count > 0 && sp.ReturnModels.First().Count > 0)            sb.AppendFormat((sp.Parameters.Count > 0 ?  ", " : "") + "out int procResult");        return sb.ToString();    };        Func<StoredProcedure, string> WriteStoredProcFunctionOverloadCall = (sp) =>    {        var sb = new StringBuilder();        foreach (var p in sp.Parameters.OrderBy(x => x.Ordinal))        {            sb.AppendFormat("{0}{1}, ",                 p.Mode == StoredProcedureParameterMode.In ? "" : "out ",                 p.NameHumanCase);        }        sb.Append("out procResult");        return sb.ToString();    };
    Func<StoredProcedure, string> WriteStoredProcFunctionSqlAtParams = sp =>    {        var sb = new StringBuilder();        int n = 1;        int count = sp.Parameters.Count;        foreach (var p in sp.Parameters.OrderBy(x => x.Ordinal))        {            sb.AppendFormat("{0}{1}{2}",                 p.Name,                 p.Mode == StoredProcedureParameterMode.In ? string.Empty : " OUTPUT",                 (n++ < count) ? ", " : string.Empty);        }        return sb.ToString();    };
    Func<StoredProcedureParameter, string> WriteStoredProcSqlParameterName = p => p.NameHumanCase + "Param";
    Func<StoredProcedure, string> WriteStoredProcFunctionDeclareSqlParameter = sp =>    {        var sb = new StringBuilder();        foreach (var p in sp.Parameters.OrderBy(x => x.Ordinal))        {            bool isNullable = !NotNullable.Contains(p.PropertyType.ToLower());            var getValueOrDefault = isNullable ? ".GetValueOrDefault()" : string.Empty;
            sb.AppendLine(string.Format("            var {0} = new System.Data.SqlClient.SqlParameter {{ ParameterName = \"{1}\", SqlDbType = System.Data.SqlDbType.{2}, Direction = System.Data.ParameterDirection.{3}{4}{5}{6}{7} }};",                 WriteStoredProcSqlParameterName(p),                 p.Name,                 p.SqlDbType,                 p.Mode == StoredProcedureParameterMode.In ? "Input" : "Output",                p.Mode == StoredProcedureParameterMode.In ? ", Value = " + p.NameHumanCase + getValueOrDefault : string.Empty,                p.MaxLength > 0 ? ", Size = " + p.MaxLength : string.Empty,                (p.Precision > 0 || p.Scale > 0) ? ", Precision = " + p.Precision + ", Scale = " + p.Scale : string.Empty,                p.PropertyType.ToLower().Contains("datatable") ? ", TypeName = \"" + p.UserDefinedTypeName + "\"" : string.Empty));
                if (p.Mode == StoredProcedureParameterMode.In)                {                    sb.AppendFormat(                        isNullable                            ? "            if (!{0}.HasValue){1}                {0}Param.Value = System.DBNull.Value;{1}{1}"                            : "            if ({0}Param.Value == null){1}                {0}Param.Value = System.DBNull.Value;{1}{1}",                        p.NameHumanCase, Environment.NewLine);                }        }        if(sp.ReturnModels.Count < 2)            sb.AppendLine("            var procResultParam = new System.Data.SqlClient.SqlParameter { ParameterName = \"@procResult\", SqlDbType = System.Data.SqlDbType.Int, Direction = System.Data.ParameterDirection.Output };");        return sb.ToString();    };
    Func<StoredProcedure, string> WriteTableValuedFunctionDeclareSqlParameter = sp =>    {        var sb = new StringBuilder();        foreach (var p in sp.Parameters.OrderBy(x => x.Ordinal))        {            var getValueOrDefault = NotNullable.Contains(p.PropertyType.ToLower()) ? string.Empty : ".GetValueOrDefault()";                sb.AppendLine(string.Format("            var {0}Param = new System.Data.Entity.Core.Objects.ObjectParameter(\"{1}\", {2});",                 p.NameHumanCase,                 p.Name.Substring(1),                 p.Mode == StoredProcedureParameterMode.In ? p.NameHumanCase + getValueOrDefault : string.Empty));        }        return sb.ToString();    };
    Func<StoredProcedure, string> WriteStoredProcFunctionSqlParameterAnonymousArray = sp =>    {        var sb = new StringBuilder();        foreach (var p in sp.Parameters.OrderBy(x => x.Ordinal))        {            sb.Append(string.Format("{0}Param, ", p.NameHumanCase));        }        sb.Append("procResultParam");        return sb.ToString();    };        Func<StoredProcedure, string> WriteTableValuedFunctionSqlParameterAnonymousArray = sp =>    {        if (sp.Parameters.Count == 0)             return "new System.Data.Entity.Core.Objects.ObjectParameter[] { }";        var sb = new StringBuilder();        foreach (var p in sp.Parameters.OrderBy(x => x.Ordinal))        {            sb.Append(string.Format("{0}Param, ", p.NameHumanCase));        }        return sb.ToString().Substring(0, sb.Length - 2);    };
    Func<StoredProcedure, bool, string> WriteStoredProcFunctionSetSqlParameters = (sp, isFake) =>    {        var sb = new StringBuilder();        foreach (var p in sp.Parameters.Where(x => x.Mode != StoredProcedureParameterMode.In).OrderBy(x => x.Ordinal))        {            string Default = string.Format("default({0})", p.PropertyType);            bool notNullable = NotNullable.Contains(p.PropertyType.ToLower());
            if(isFake)                sb.AppendLine(string.Format("            {0} = {1};", p.NameHumanCase, Default));            else            {                sb.AppendLine(string.Format("            if (IsSqlParameterNull({0}Param))", p.NameHumanCase));                sb.AppendLine(string.Format("                {0} = {1};", p.NameHumanCase, notNullable ? Default : "null"));                sb.AppendLine("            else");                sb.AppendLine(string.Format("                {0} = ({1}) {2}Param.Value;", p.NameHumanCase, p.PropertyType, p.NameHumanCase));            }        }        return sb.ToString();    };
    Func<StoredProcedure, string> WriteStoredProcReturnModelName = sp =>        StoredProcedureReturnTypes.ContainsKey(sp.NameHumanCase)            ? StoredProcedureReturnTypes[sp.NameHumanCase]            : StoredProcedureReturnTypes.ContainsKey(sp.Name)                ? StoredProcedureReturnTypes[sp.Name]                : string.Format("{0}ReturnModel", sp.NameHumanCase);
    Func<DataColumn, string> WriteStoredProcReturnColumn = col =>         string.Format("public System.{0}{1}{2} {{ get; set; }}",            col.DataType.Name, StoredProcedure.CheckNullable(col), col.ColumnName);
    Func<StoredProcedure, string> WriteStoredProcReturnType = (sp) =>    {        var returnModelCount = sp.ReturnModels.Count;        if (returnModelCount == 0)            return "int";
        var spReturnClassName = WriteStoredProcReturnModelName(sp);        return (returnModelCount == 1) ? string.Format("System.Collections.Generic.List<{0}>", spReturnClassName) : spReturnClassName;    };
        // That's it, nothing else to configure ***********************************************************************************************                // Read schema    var factory = GetDbProviderFactory();    IsSqlCe = IsSqlCeConnection(factory);    var tables = LoadTables(factory);    var storedProcs = LoadStoredProcs(factory);        // Generate output    if (tables.Count > 0 || storedProcs.Count > 0)    {#><#@ include file="EF.Reverse.POCO.ttinclude" #><#@ import namespace="System.Xml.Schema" #><# } #>

EF.Reverse.POCO.Core.ttinclude"的更多相关文章

  1. EntityFramework Reverse POCO Code First 生成器

    功能强大的(免费)实体框架工具 Julie Lerman 实体框架是开源的,因此开发社区可以在 entityframework.codeplex.com 上共享代码. 但是不要将自己局限在那里寻找工具 ...

  2. EF之POCO应用系列3——延迟加载

    EF之POCO应用系列4——延迟加载 当我们进行查询的时候,哪些关系的数据将会被加载到内存呢?所有相关的对象都需要吗?在一些场合可能有意义,例如,当查询的实体仅仅拥有一个相关的子实体,但是,多数情况下 ...

  3. EF之POCO应用系列2——复杂类型

    在.NET开发中,EF4以前的版本以及LINQ TO SQL都不支持complex数据类型,EF4终于支持complex类型的数据了,这意味着微软的EF框架朝领域驱动方面又迈了一大步. 复杂的数据类型 ...

  4. EntityFramework Reverse POCO Generator工具

    https://visualstudiogallery.msdn.microsoft.com/ee4fcff9-0c4c-4179-afd9-7a2fb90f5838

  5. PetaPoco.Core.ttinclude修改

    /// <summary> /// Adds the singular rule. /// </summary> /// <param name="rule&q ...

  6. EntityFramework Reverse POCO Code First 反向生成器

    https://marketplace.visualstudio.com/items?itemName=SimonHughes.EntityFrameworkReversePOCOGenerator ...

  7. EF Entity Framework Core DBContext中文文档

    Add(Object) 以添加状态开始跟踪给定的实体和任何其他尚未被跟踪的可访问实体,以便在调用SaveChanges()时将它们插入数据库.使用State设置单个实体的状态. Add<TEnt ...

  8. Entity Framework工具POCO Code First Generator的使用

    在使用Entity Framework过程中,有时需要借助工具生成Code First的代码,而Entity Framework Reverse POCO Code First Generator是一 ...

  9. Entity Framework工具POCO Code First Generator的使用(参考链接:https://github.com/sjh37/EntityFramework-Reverse-POCO-Code-First-Generator)

    在使用Entity Framework过程中,有时需要借助工具生成Code First的代码,而Entity Framework Reverse POCO Code First Generator是一 ...

随机推荐

  1. 用hibernate.properties代替hibernate.cfg.xml配置常用的属性

    我们使用hibernate时经常在hibernate.cfg.xml文件中配置数据库连接的相关属性,是否显示sql语句,数据库的方言等,这些配置其实也可以在.properties文件中配置.现在我把这 ...

  2. python装饰器(整理版)

    Python中函数有一个装饰器的概念,今天,看核心编程中的函数一章的时候接触到了这个概念,炸一看来,讲的说明真实不好明白.于是写下本篇以示说明,提供给迷糊者.希望能对一些人起到一定的帮助 装饰器的语法 ...

  3. RSA解密报错java.security.spec.InvalidKeySpecException的解决办法

    java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException : algid p ...

  4. Python-Python及PyCharm的下载与安装

    一.简介 Python:英 -[‘paɪθ ə n]或[‘paɪθɑn] 89年诞生 可用于软件开发: 游戏后台.搜索.图形界面 网站 C\S(Client/Server)软件 科学计算 亦可以进行系 ...

  5. [ CodeVS冲杯之路 ] P1068

    不充钱,你怎么AC? 题目:http://codevs.cn/problem/1068/ 这是一道神DP题,一开始状态设计错了,用位置和剩余卡片做下标,过了样例数据WA了 好了,讲正解,设 f[i][ ...

  6. [ CodeVS冲杯之路 ] P3145

     不充钱,你怎么AC? 题目:http://codevs.cn/problem/3145/ 经典的汉诺塔问题 我们移动的时候,如果是最小的1号就可以直接移动,否则先将上面的x-1号先移动到借用塔上,然 ...

  7. "贪心"的考试

    先来落实比较简单的T3,T4 T3  团结的队伍 team 题目描述 众所周知,长郡信息组是一个团结友爱的优秀团队.为了弘扬团队精神,践行社会主义核心价值观,秉承朴实沉毅的校训,信息组决定外出游玩(. ...

  8. PHP会话控制

         会话控制的思想是指能够在网站中根据一个会话跟踪用户.      PHP的会话是通过唯一的会话ID来驱动的.会话ID是一个加密的随机数字.它由PHP生成,在会话的生命周期中都会保存在客户端.它 ...

  9. VS程序打包软件

    由于InstallShield Limited Edition for Visual Studio的教程.资料太少,所以我今天才决定写这个文章,专门针对C#项目打包,包括打包集成Microsoft . ...

  10. Linux平台用C++实现事件对象,同步线程

    前文在Win32平台上用C++实现了事件对象Event,对线程进行同步,以达到期望目的.这次在Linux平台上实现与之类似的事件对象.与其相关的一组API包括:pthread_mutex_init,p ...