Entity Framework工具POCO Code First Generator的使用

来源:http://www.cnblogs.com/godbell/archive/2017/08/29/7450547.html
-Advertisement-
Play Games

在使用Entity Framework過程中,有時需要藉助工具生成Code First的代碼,而Entity Framework Reverse POCO Code First Generator是一款不錯的工具 在Visual Studio中,通過“工具”→“擴展和更新...”來安裝Entity ...


在使用Entity Framework過程中,有時需要藉助工具生成Code First的代碼,而Entity Framework Reverse POCO Code First Generator是一款不錯的工具

在Visual Studio中,通過“工具”→“擴展和更新...”來安裝Entity Framework Reverse POCO Code First Generator

 

這裡添加一個控制台項目,併在項目中添加POCO Code First Generator 生成模板(註意:添加項目後需要添加Entity Framework,POCO Code First Generator藉助Entity Framework生成代碼,可以使用Nuget添加)

 

 

預設的生成模板如下:

<#@ include file="EF.Reverse.POCO.Core.ttinclude" #>
<#
    // v2.32.0
    // 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).
    // A course for this generator is available on Pluralsight at https://www.pluralsight.com/courses/code-first-entity-framework-legacy-databases

    // Main settings **********************************************************************************************************************
    ConnectionStringName = "MyDbContext";   // Searches for this connection string in config files listed below in the ConfigFilenameSearchOrder setting
    // ConnectionStringName is the only required setting.
    // As an alternative to ConnectionStringName above, which must match your app/web.config connection string name, you can override them below
    //ConnectionString = "Data Source=(local);Initial Catalog=Northwind;Integrated Security=True;Application Name=EntityFramework Reverse POCO Generator";
    //ProviderName = "System.Data.SqlClient";

    // Namespace = ""; // Override the default namespace here
    DbContextName = "MyDbContext"; // Note: If generating separate files, please give the db context a different name from this tt filename.
    //DbContextInterfaceName = "IMyDbContext"; // Defaults to "I" + DbContextName or set string empty to not implement any interface.
    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>"
    //DefaultConstructorArgument = "EnvironmentConnectionStrings.MyDbContext"; //defaults to "Name=" + ConnectionStringName
    ConfigurationClassName = "Configuration"; // Configuration, Mapping, Map, etc. This is appended to the Poco class name to configure the mappings.
    ConfigFilenameSearchOrder = new[] { "app.config", "web.config" }; // Add more here if required. The config files are searched for in the local project first, then the whole solution second.
    GenerateSeparateFiles = false;
    MakeClassesInternal = false;
    MakeClassesPartial = false;
    MakeDbContextInterfacePartial = false;
    UseMappingTables = true; // If true, mapping will be used and no mapping tables will be generated. If false, all tables will be generated.
    UsePascalCase = true;    // This will rename the generated C# tables & properties to use PascalCase. If false table & property names will be left alone.
    UseDataAnnotations = false; // If true, will add data annotations to the poco classes.
    UseDataAnnotationsSchema = false; // UseDataAnnotations must also be true. If true, will add data annotations schema to the poco classes.
    UsePropertyInitializers = false; // Removes POCO constructor and instead uses C# 6 property initialisers to set defaults
    UseLazyLoading = true; // Marks all navigation properties as virtual or not, to support or disable EF Lazy Loading feature
    IncludeComments = CommentsStyle.AtEndOfField; // Adds comments to the generated code
    IncludeExtendedPropertyComments = CommentsStyle.InSummaryBlock; // Adds extended properties as comments to the generated code
    IncludeConnectionSettingComments = true; // Add comments describing connection settings used to generate file
    IncludeViews = true;
    IncludeSynonyms = false;
    IncludeStoredProcedures = true;
    IncludeTableValuedFunctions = false; // If true, you must set IncludeStoredProcedures = true, and 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.
    //CollectionInterfaceType = "System.Collections.Generic.List"; // Determines the declaration type of collections for the Navigation Properties. ICollection is used if not set.
    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".
    NullableShortHand = true; //true => T?, false => Nullable<T>
    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).
    IncludeCodeGeneratedAttribute = true; // If true, will include the GeneratedCode attribute, false to remove it.
    UsePrivateSetterForComputedColumns = true; // If the columns is computed, use a private setter.
    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.
    // For more control, take a look at ForeignKeyAnnotationsProcessing() further down
    AdditionalReverseNavigationsDataAnnotations = new string[] // Data Annotations for all ReverseNavigationProperty.
    {
        // "JsonIgnore" // Also add "Newtonsoft.Json" to the AdditionalNamespaces array above
    };
    AdditionalForeignKeysDataAnnotations = new string[] // Data Annotations for all ForeignKeys.
    {
        // "JsonIgnore" // Also add "Newtonsoft.Json" to the AdditionalNamespaces array above
    };
    ColumnNameToDataAnnotation = new Dictionary<string, string>
    {
        // This is used when UseDataAnnotations = true;
        // It is used to set a data annotation on a column based on the columns name.
        // Make sure the column name is lowercase in the following array, regardless of how it is in the database
        // Column name       DataAnnotation to add
        { "email",           "EmailAddress" },
        { "emailaddress",    "EmailAddress" },
        { "creditcard",      "CreditCard" },
        { "url",             "Url" },
        { "phone",           "Phone" },
        { "phonenumber",     "Phone" },
        { "mobile",          "Phone" },
        { "mobilenumber",    "Phone" },
        { "telephone",       "Phone" },
        { "telephonenumber", "Phone" },
        { "password",        "DataType(DataType.Password)" },
        { "username",        "DataType(DataType.Text)" }
    };

    // 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();
    // If pluralisation does not do the right thing, override it here by adding in a custom entry.
    //Inflector.PluralizationService = new EnglishPluralizationService(new[]
    //{
    //    // Create custom ("Singular", "Plural") forms for one-off words as needed.
    //    new CustomPluralizationEntry("Course", "Courses"),
    //    new CustomPluralizationEntry("Status", "Status") // Use same value to prevent pluralisation
    //});


    // 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.
    // 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

    // Table Suffix ***********************************************************************************************************************
    // Prepends 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
    TableSuffix = null;

    // 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.
    // For clarity: if you want to include all the customer tables, but not the customer billing tables.
    //      TableFilterInclude = new Regex("^[Cc]ustomer.*"); // This includes all the customer and customer billing tables
    //      TableFilterExclude = new Regex(".*[Bb]illing.*"); // This excludes all the billing tables
    //
    // 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;

    // Filtering of tables using a function. This can be used in conjunction with the Regex's above.
    // Regex are used first to filter the list down, then this function is run last.
    // Return true to include the table, return false to exclude it.
    TableFilter = (Table t) =>
    {
        // Example: Exclude any table in dbo schema with "order" in its name.
        //if(t.Schema.Equals("dbo", StringComparison.InvariantCultureIgnoreCase) && t.NameHumanCase.ToLowerInvariant().Contains("order"))
        //    return false;

        return true;
    };


    // Stored Procedures ******************************************************************************************************************
    // Use the following regex filters to include or exclude stored procedures
    StoredProcedureFilterExclude = null;
    StoredProcedureFilterInclude = null;

    // Filtering of stored procedures using a function. This can be used in conjunction with the Regex's above.
    // Regex are used first to filter the list down, then this function is run last.
    // Return true to include the stored procedure, return false to exclude it.
    StoredProcedureFilter = (StoredProcedure sp) =>
    {
        // Example: Exclude any stored procedure in dbo schema with "order" in its name.
        //if(sp.Schema.Equals("dbo", StringComparison.InvariantCultureIgnoreCase) && sp.NameHumanCase.ToLowerInvariant().Contains("order"))
        //    return false;

        return true;
    };


    // Table renaming *********************************************************************************************************************
    // Use the following function to rename tables such as tblOrders to Orders, Shipments_AB to Shipments, etc.
    // Example:
    TableRename = (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;
    };

    // 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) =>
    {
        // 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;

        // 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 = EnumsDefinitions.FirstOrDefault(e =>
            (e.Schema.Equals(table.Schema, StringComparison.InvariantCultureIgnoreCase)) &&
            (e.Table.Equals(table.Name, StringComparison.InvariantCultureIgnoreCase) || e.Table.Equals(table.NameHumanCase, StringComparison.InvariantCultureIgnoreCase)) &&
            (e.Column.Equals(column.Name, 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;
        }

        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 = (sp) =>
    {
        if (sp.NameHumanCase.StartsWith("sp_"))
            return sp.NameHumanCase.Remove(0, 3);
        return sp.NameHumanCase.Replace("my_sp_", "");
    };*/
    StoredProcedureRename = (sp) => 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.
    // Example:
    /*StoredProcedureReturnModelRename = (name, sp) =>
    {
        if (sp.NameHumanCase.Equals("ComputeValuesForDate", StringComparison.InvariantCultureIgnoreCase))
            return "ValueSet";
        if (sp.NameHumanCase.Equals("SalesByYear", StringComparison.InvariantCultureIgnoreCase))
            return "SalesSet";

        return name;
    };*/
    StoredProcedureReturnModelRename = (name, sp) => 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");


    // Callbacks **********************************************************************************************************************
    // This method will be called right before we write the POCO header.
    Action<Table> WritePocoClassAttributes = t =>
    {
        if (UseDataAnnotations)
        {
            foreach (var dataAnnotation in t.DataAnnotations)
            {
                WriteLine("    [" + dataAnnotation + "]");
            }
        }

        // 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>";

        // Or use the maker class to dynamically build more complex definitions
        /* Example:
        var r = new BaseClassMaker("POCO.Sample.Data.MetaModelObject");
        r.AddInterface("POCO.Sample.Data.IObjectWithTableName");
        r.AddInterface("POCO.Sample.Data.IObjectWithId",
            t.Columns.Any(x => x.IsPrimaryKey && !x.IsNullable && x.NameHumanCase.Equals("Id", StringComparison.InvariantCultureIgnoreCase) && x.PropertyType == "long"));
        r.AddInterface("POCO.Sample.Data.IObjectWithUserId",
            t.Columns.Any(x => !x.IsPrimaryKey && !x.IsNullable && x.NameHumanCase.Equals("UserId", StringComparison.InvariantCultureIgnoreCase) && x.PropertyType == "long"));
        return r.ToString();
        */

        return "";
    };

    // Writes any boilerplate stuff
    Action<Table> WritePocoBaseClassBody = t =>
    {
        // Do nothing by default
        // Example:
        // WriteLine("        // " + t.ClassName);
    };

    Func<Column, string> WritePocoColumn = c =>
    {
        bool commentWritten = false;
        if((IncludeExtendedPropertyComments == CommentsStyle.InSummaryBlock || IncludeComments == CommentsStyle.InSummaryBlock) && !string.IsNullOrEmpty(c.SummaryComments))
        {
            WriteLine(string.Empty);
            WriteLine("        ///<summary>");
            WriteLine("        /// {0}", System.Security.SecurityElement.Escape(c.SummaryComments));
            WriteLine("        ///</summary>");
            commentWritten = true;
        }
        if (UseDataAnnotations)
        {
            if(c.Ordinal > 1 && !commentWritten)
                WriteLine(string.Empty);    // Leave a blank line before the next property

            foreach (var dataAnnotation in c.DataAnnotations)
            {
                WriteLine("        [" + dataAnnotation + "]");
            }
        }

        // Example of adding a [Required] data annotation attribute to all non-null fields
        //if (!c.IsNullable)
        //    return "        [System.ComponentModel.DataAnnotations.Required] " + c.Entity;

        return "        " + c.Entity;
    };

    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;

        return fk;
    };

    ForeignKeyProcessing = (foreignKeys, fkTable, pkTable, anyNullableColumnInForeignKey) =>
    {
        var foreignKey = foreignKeys.First();

        // If using data annotations and to include the [Required] attribute in the foreign key, enable the following
        //if (!anyNullableColumnInForeignKey)
        //   foreignKey.IncludeRequiredAttribute = true;

        return foreignKey;
    };

    ForeignKeyName = (tableName, foreignKey, foreignKeyName, relationship, 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;
    };

    ForeignKeyAnnotationsProcessing = (Table fkTable, Table pkTable, string propName) =>
    {
        /* 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;
    };

    // Return true to include this table in the db context
    ConfigurationFilter = (Table t) =>
    {
        return true;
    };

    // That's it, nothing else to configure ***********************************************************************************************


    // Read schema
    var factory = GetDbProviderFactory();
    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" #>
<# } #>
View Code

在App.config中添加資料庫連接字元串,如果是Web項目,則是Web.config,這裡name與POCO 模板指定的Name一致(可以修改模板或配置文件,隨便一處,保持一致就行)

在模板中Ctrl + S,這時提示運行模板,點擊“確定”

這是生成的代碼:

參考鏈接:https://github.com/sjh37/EntityFramework-Reverse-POCO-Code-First-Generator

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 用戶登錄是一個非常常見的應用場景 .net core 2.0 的登錄方式發生了點變化,應該是屬於是良性的變化,變得更方便,更容易擴展。 打開項目中的Startup.cs文件,找到ConfigureServices方法,我們通常在這個方法裡面做依賴註入的相關配置。添加如下代碼: ...
  • 最近研究微信項目,套著web版微信協議做了一個客戶端,整體WPF項目MVVM架構及基本代碼參考於:http://www.cnblogs.com/ZXdeveloper/archive/2016/11/13/6058206.html 由於參考博主的項目沒有實現RichTextBox綁定圖片與後臺接收圖 ...
  • Spire.Pdf: 註:pdf 顯示中文一定要設置相應的中文字體,其他外文類似。否則顯示為亂碼( 如果繁體的伺服器上生成的中文內容PDF文檔,在簡體操作系統保存或並傳給簡體系統上查看,會存在亂碼問題,這個需要考慮的) 安裝配置:PM> Install-Package Spire.PDF https ...
  • C# using 三種使用方式 http://www.cnblogs.com/dachengxiaomeng/p/7452021.html 1.using指令。 using 命名空間名字。例如: using System; 這樣可以在程式中直接用命令空間中的類型,而不必指定類型的詳細命名空間,類似於 ...
  • jQuery的方法連綴使用起來非常方便,可以簡化語句,讓代碼變得清晰簡潔。那C#的類方法能不能也實現類似的功能呢?基於這樣的疑惑,研究了一下jQuery的源代碼,發現就是需要方法連綴的函數方法最後返回對象本身即可。既然javascript可以,C#應該也是可以的。 為了驗證,編寫一個jQPerson ...
  • 最近在做項目進度管理時,想通過安裝net.sf.mpxj-for-csharp包讀取.mpp格式文件,通過Nuget線上安裝時,出現以下情況,無法安裝,故開啟離線安裝道路。 離線安裝步驟如下: 一、下載你需要安裝的離線包nupkg文件,可以在Nuget官網下載:https://www.nuget.o ...
  • 最近在開始一個微信開發,發現微信的Access_Token獲取每天次數是有限的,然後想到緩存,正好看到微信教程裡面推薦HttpRuntime.Cache緩存就順便看了下。 ...
  • //設置對話框的過濾條件 ofdSelectPic.Filter = "png文件(*.png)|*.png|jpg 文件(*.jpg)|*.jpg|所有文件(*.*)|*.*"; ofdSelectPic.Title = "打開圖片"; ofdSelectPic.FilterIndex = 2; ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...