• 【转】Entity Framework 5.0系列之自动生成Code First代码


    在前面的文章中我们提到Entity Framework的“Code First”模式也同样可以基于现有数据库进行开发。今天就让我们一起看一下使用Entity Framework Power Tools如何基于现有数据库生成数据类和数据库上下等。

    Entity Framework Power Tools

    基于现有数据库生成POCO数据类和数据库上下文需要借助Visual Studio一个扩展插件-- Entity Framework Power Tools(一个Code First反向工程工具)。只要在Visual Studio扩展里面输入“Entity Framework Power”搜索即可找到最新的扩展,点击下载即可(如下图)。当然你也可以到这里Entity Framework Power Tools Beta 3下载安装包进行安装。

    安装完之后只要在项目上右键选择Entity Framework->Reverse Engineer Code First(项目中首先需要安装Entity Framework 包,否则会有错误),然后在弹出的窗口中输入相关的数据库连接信息即可(我们这里使用“AdventureWorks”数据库)。

    note

    注意:如果使用“AdventureWorks”数据库,可能发生如下错误:

    One or more errors occurred while loading schema information.

    error 6004: The table 'AdventureWorks.Production.Document' is referenced by a relationship, but cannot be found.

    这是由于EF目前还不支持SQL Server 2008中新增的“Hierarchyid”数据类型,目前只有先不用该类型的数据了,暂时将它改为其他类型。

    然后我们稍等片刻,可以看到Entity Framework Power Tools已经根据所选数据库自动为你生成了数据类、数据库上下文操作类、对应的映射配置类并添加了数据库连接配置。

    我们先看一下配置文件,可以看到在配置文件中Entity Framework Power Tools已经自动对数据库连接串进行了配置,添加了名为“AdventureWorksContext”的数据库连接串:

    1. <?xml version="1.0" encoding="utf-8"?>  
    2. <configuration>  
    3.   <configSections>  
    4.     <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->  
    5.     <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />  
    6.   </configSections>  
    7.   <connectionStrings>  
    8.     <add name="AdventureWorksContext" connectionString="Data Source=.SQL2008;Initial Catalog=AdventureWorks;Persist Security Info=True;User ID=sa;Password=123;MultipleActiveResultSets=True"  
    9.       providerName="System.Data.SqlClient" />  
    10.   </connectionStrings>  
    11.   <startup>  
    12.     <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />  
    13.   </startup>  
    14.   <entityFramework>  
    15.     <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">  
    16.       <parameters>  
    17.         <parameter value="v11.0" />  
    18.       </parameters>  
    19.     </defaultConnectionFactory>  
    20.   </entityFramework>  
    21. </configuration>  
    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
      <configSections>
        <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
        <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
      </configSections>
      <connectionStrings>
        <add name="AdventureWorksContext" connectionString="Data Source=.SQL2008;Initial Catalog=AdventureWorks;Persist Security Info=True;User ID=sa;Password=123;MultipleActiveResultSets=True"
          providerName="System.Data.SqlClient" />
      </connectionStrings>
      <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
      </startup>
      <entityFramework>
        <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
          <parameters>
            <parameter value="v11.0" />
          </parameters>
        </defaultConnectionFactory>
      </entityFramework>
    </configuration>

    与此同时,对生成的数据库上下文操作类“AdventureWorksContext”进行了配置,在构造函数中使用了上面配置的“AdventureWorksContext”数据库连接:

    1. using System.Data.Entity;  
    2. using System.Data.Entity.Infrastructure;  
    3. using EFPowerTools.Models.Mapping;  
    4.   
    5. namespace EFPowerTools.Models  
    6. {  
    7.     public partial class AdventureWorksContext : DbContext  
    8.     {  
    9.         static AdventureWorksContext()  
    10.         {  
    11.             Database.SetInitializer<AdventureWorksContext>(null);  
    12.         }  
    13.   
    14.         public AdventureWorksContext()  
    15.             : base("Name=AdventureWorksContext")  
    16.         {  
    17.         }  
    18.   
    19.         public DbSet<AWBuildVersion> AWBuildVersions { get; set; }  
    20.         public DbSet<DatabaseLog> DatabaseLogs { get; set; }  
    21.         public DbSet<ErrorLog> ErrorLogs { get; set; }  
    22.         public DbSet<OrderDetail> OrderDetails { get; set; }  
    23.         public DbSet<Order> Orders { get; set; }  
    24.         public DbSet<Department> Departments { get; set; }  
    25.         public DbSet<Employee> Employees { get; set; }  
    26.         public DbSet<EmployeeDepartmentHistory> EmployeeDepartmentHistories { get; set; }  
    27.         public DbSet<EmployeePayHistory> EmployeePayHistories { get; set; }  
    28.         public DbSet<JobCandidate> JobCandidates { get; set; }  
    29.         public DbSet<Shift> Shifts { get; set; }  
    30.         public DbSet<Address> Addresses { get; set; }  
    31.         public DbSet<AddressType> AddressTypes { get; set; }  
    32.         public DbSet<BusinessEntity> BusinessEntities { get; set; }  
    33.         public DbSet<BusinessEntityAddress> BusinessEntityAddresses { get; set; }  
    34.         public DbSet<BusinessEntityContact> BusinessEntityContacts { get; set; }  
    35.         public DbSet<ContactType> ContactTypes { get; set; }  
    36.         public DbSet<CountryRegion> CountryRegions { get; set; }  
    37.         public DbSet<EmailAddress> EmailAddresses { get; set; }  
    38.         public DbSet<Password> Passwords { get; set; }  
    39.         public DbSet<Person> People { get; set; }  
    40.         public DbSet<PersonPhone> PersonPhones { get; set; }  
    41.         public DbSet<PhoneNumberType> PhoneNumberTypes { get; set; }  
    42.         public DbSet<StateProvince> StateProvinces { get; set; }  
    43.         public DbSet<BillOfMaterial> BillOfMaterials { get; set; }  
    44.         public DbSet<Culture> Cultures { get; set; }  
    45.         public DbSet<Illustration> Illustrations { get; set; }  
    46.         public DbSet<Location> Locations { get; set; }  
    47.         public DbSet<Product> Products { get; set; }  
    48.         public DbSet<ProductCategory> ProductCategories { get; set; }  
    49.         public DbSet<ProductCostHistory> ProductCostHistories { get; set; }  
    50.         public DbSet<ProductDescription> ProductDescriptions { get; set; }  
    51.         public DbSet<ProductInventory> ProductInventories { get; set; }  
    52.         public DbSet<ProductListPriceHistory> ProductListPriceHistories { get; set; }  
    53.         public DbSet<ProductModel> ProductModels { get; set; }  
    54.         public DbSet<ProductModelIllustration> ProductModelIllustrations { get; set; }  
    55.         public DbSet<ProductModelProductDescriptionCulture> ProductModelProductDescriptionCultures { get; set; }  
    56.         public DbSet<ProductPhoto> ProductPhotoes { get; set; }  
    57.         public DbSet<ProductProductPhoto> ProductProductPhotoes { get; set; }  
    58.         public DbSet<ProductReview> ProductReviews { get; set; }  
    59.         public DbSet<ProductSubcategory> ProductSubcategories { get; set; }  
    60.         public DbSet<ScrapReason> ScrapReasons { get; set; }  
    61.         public DbSet<TransactionHistory> TransactionHistories { get; set; }  
    62.         public DbSet<TransactionHistoryArchive> TransactionHistoryArchives { get; set; }  
    63.         public DbSet<UnitMeasure> UnitMeasures { get; set; }  
    64.         public DbSet<WorkOrder> WorkOrders { get; set; }  
    65.         public DbSet<WorkOrderRouting> WorkOrderRoutings { get; set; }  
    66.         public DbSet<ProductVendor> ProductVendors { get; set; }  
    67.         public DbSet<PurchaseOrderDetail> PurchaseOrderDetails { get; set; }  
    68.         public DbSet<PurchaseOrderHeader> PurchaseOrderHeaders { get; set; }  
    69.         public DbSet<ShipMethod> ShipMethods { get; set; }  
    70.         public DbSet<Vendor> Vendors { get; set; }  
    71.         public DbSet<CountryRegionCurrency> CountryRegionCurrencies { get; set; }  
    72.         public DbSet<CreditCard> CreditCards { get; set; }  
    73.         public DbSet<Currency> Currencies { get; set; }  
    74.         public DbSet<CurrencyRate> CurrencyRates { get; set; }  
    75.         public DbSet<Customer> Customers { get; set; }  
    76.         public DbSet<PersonCreditCard> PersonCreditCards { get; set; }  
    77.         public DbSet<SalesOrderDetail> SalesOrderDetails { get; set; }  
    78.         public DbSet<SalesOrderHeader> SalesOrderHeaders { get; set; }  
    79.         public DbSet<SalesOrderHeaderSalesReason> SalesOrderHeaderSalesReasons { get; set; }  
    80.         public DbSet<SalesPerson> SalesPersons { get; set; }  
    81.         public DbSet<SalesPersonQuotaHistory> SalesPersonQuotaHistories { get; set; }  
    82.         public DbSet<SalesReason> SalesReasons { get; set; }  
    83.         public DbSet<SalesTaxRate> SalesTaxRates { get; set; }  
    84.         public DbSet<SalesTerritory> SalesTerritories { get; set; }  
    85.         public DbSet<SalesTerritoryHistory> SalesTerritoryHistories { get; set; }  
    86.         public DbSet<ShoppingCartItem> ShoppingCartItems { get; set; }  
    87.         public DbSet<SpecialOffer> SpecialOffers { get; set; }  
    88.         public DbSet<SpecialOfferProduct> SpecialOfferProducts { get; set; }  
    89.         public DbSet<Store> Stores { get; set; }  
    90.         public DbSet<vEmployee> vEmployees { get; set; }  
    91.         public DbSet<vEmployeeDepartment> vEmployeeDepartments { get; set; }  
    92.         public DbSet<vEmployeeDepartmentHistory> vEmployeeDepartmentHistories { get; set; }  
    93.         public DbSet<vJobCandidate> vJobCandidates { get; set; }  
    94.         public DbSet<vJobCandidateEducation> vJobCandidateEducations { get; set; }  
    95.         public DbSet<vJobCandidateEmployment> vJobCandidateEmployments { get; set; }  
    96.         public DbSet<vAdditionalContactInfo> vAdditionalContactInfoes { get; set; }  
    97.         public DbSet<vStateProvinceCountryRegion> vStateProvinceCountryRegions { get; set; }  
    98.         public DbSet<vProductAndDescription> vProductAndDescriptions { get; set; }  
    99.         public DbSet<vProductModelCatalogDescription> vProductModelCatalogDescriptions { get; set; }  
    100.         public DbSet<vProductModelInstruction> vProductModelInstructions { get; set; }  
    101.         public DbSet<vVendorWithAddress> vVendorWithAddresses { get; set; }  
    102.         public DbSet<vVendorWithContact> vVendorWithContacts { get; set; }  
    103.         public DbSet<vIndividualCustomer> vIndividualCustomers { get; set; }  
    104.         public DbSet<vPersonDemographic> vPersonDemographics { get; set; }  
    105.         public DbSet<vSalesPerson> vSalesPersons { get; set; }  
    106.         public DbSet<vSalesPersonSalesByFiscalYear> vSalesPersonSalesByFiscalYears { get; set; }  
    107.         public DbSet<vStoreWithAddress> vStoreWithAddresses { get; set; }  
    108.         public DbSet<vStoreWithContact> vStoreWithContacts { get; set; }  
    109.         public DbSet<vStoreWithDemographic> vStoreWithDemographics { get; set; }  
    110.   
    111.         protected override void OnModelCreating(DbModelBuilder modelBuilder)  
    112.         {  
    113.             modelBuilder.Configurations.Add(new AWBuildVersionMap());  
    114.             modelBuilder.Configurations.Add(new DatabaseLogMap());  
    115.             modelBuilder.Configurations.Add(new ErrorLogMap());  
    116.             modelBuilder.Configurations.Add(new OrderDetailMap());  
    117.             modelBuilder.Configurations.Add(new OrderMap());  
    118.             modelBuilder.Configurations.Add(new DepartmentMap());  
    119.             modelBuilder.Configurations.Add(new EmployeeMap());  
    120.             modelBuilder.Configurations.Add(new EmployeeDepartmentHistoryMap());  
    121.             modelBuilder.Configurations.Add(new EmployeePayHistoryMap());  
    122.             modelBuilder.Configurations.Add(new JobCandidateMap());  
    123.             modelBuilder.Configurations.Add(new ShiftMap());  
    124.             modelBuilder.Configurations.Add(new AddressMap());  
    125.             modelBuilder.Configurations.Add(new AddressTypeMap());  
    126.             modelBuilder.Configurations.Add(new BusinessEntityMap());  
    127.             modelBuilder.Configurations.Add(new BusinessEntityAddressMap());  
    128.             modelBuilder.Configurations.Add(new BusinessEntityContactMap());  
    129.             modelBuilder.Configurations.Add(new ContactTypeMap());  
    130.             modelBuilder.Configurations.Add(new CountryRegionMap());  
    131.             modelBuilder.Configurations.Add(new EmailAddressMap());  
    132.             modelBuilder.Configurations.Add(new PasswordMap());  
    133.             modelBuilder.Configurations.Add(new PersonMap());  
    134.             modelBuilder.Configurations.Add(new PersonPhoneMap());  
    135.             modelBuilder.Configurations.Add(new PhoneNumberTypeMap());  
    136.             modelBuilder.Configurations.Add(new StateProvinceMap());  
    137.             modelBuilder.Configurations.Add(new BillOfMaterialMap());  
    138.             modelBuilder.Configurations.Add(new CultureMap());  
    139.             modelBuilder.Configurations.Add(new IllustrationMap());  
    140.             modelBuilder.Configurations.Add(new LocationMap());  
    141.             modelBuilder.Configurations.Add(new ProductMap());  
    142.             modelBuilder.Configurations.Add(new ProductCategoryMap());  
    143.             modelBuilder.Configurations.Add(new ProductCostHistoryMap());  
    144.             modelBuilder.Configurations.Add(new ProductDescriptionMap());  
    145.             modelBuilder.Configurations.Add(new ProductInventoryMap());  
    146.             modelBuilder.Configurations.Add(new ProductListPriceHistoryMap());  
    147.             modelBuilder.Configurations.Add(new ProductModelMap());  
    148.             modelBuilder.Configurations.Add(new ProductModelIllustrationMap());  
    149.             modelBuilder.Configurations.Add(new ProductModelProductDescriptionCultureMap());  
    150.             modelBuilder.Configurations.Add(new ProductPhotoMap());  
    151.             modelBuilder.Configurations.Add(new ProductProductPhotoMap());  
    152.             modelBuilder.Configurations.Add(new ProductReviewMap());  
    153.             modelBuilder.Configurations.Add(new ProductSubcategoryMap());  
    154.             modelBuilder.Configurations.Add(new ScrapReasonMap());  
    155.             modelBuilder.Configurations.Add(new TransactionHistoryMap());  
    156.             modelBuilder.Configurations.Add(new TransactionHistoryArchiveMap());  
    157.             modelBuilder.Configurations.Add(new UnitMeasureMap());  
    158.             modelBuilder.Configurations.Add(new WorkOrderMap());  
    159.             modelBuilder.Configurations.Add(new WorkOrderRoutingMap());  
    160.             modelBuilder.Configurations.Add(new ProductVendorMap());  
    161.             modelBuilder.Configurations.Add(new PurchaseOrderDetailMap());  
    162.             modelBuilder.Configurations.Add(new PurchaseOrderHeaderMap());  
    163.             modelBuilder.Configurations.Add(new ShipMethodMap());  
    164.             modelBuilder.Configurations.Add(new VendorMap());  
    165.             modelBuilder.Configurations.Add(new CountryRegionCurrencyMap());  
    166.             modelBuilder.Configurations.Add(new CreditCardMap());  
    167.             modelBuilder.Configurations.Add(new CurrencyMap());  
    168.             modelBuilder.Configurations.Add(new CurrencyRateMap());  
    169.             modelBuilder.Configurations.Add(new CustomerMap());  
    170.             modelBuilder.Configurations.Add(new PersonCreditCardMap());  
    171.             modelBuilder.Configurations.Add(new SalesOrderDetailMap());  
    172.             modelBuilder.Configurations.Add(new SalesOrderHeaderMap());  
    173.             modelBuilder.Configurations.Add(new SalesOrderHeaderSalesReasonMap());  
    174.             modelBuilder.Configurations.Add(new SalesPersonMap());  
    175.             modelBuilder.Configurations.Add(new SalesPersonQuotaHistoryMap());  
    176.             modelBuilder.Configurations.Add(new SalesReasonMap());  
    177.             modelBuilder.Configurations.Add(new SalesTaxRateMap());  
    178.             modelBuilder.Configurations.Add(new SalesTerritoryMap());  
    179.             modelBuilder.Configurations.Add(new SalesTerritoryHistoryMap());  
    180.             modelBuilder.Configurations.Add(new ShoppingCartItemMap());  
    181.             modelBuilder.Configurations.Add(new SpecialOfferMap());  
    182.             modelBuilder.Configurations.Add(new SpecialOfferProductMap());  
    183.             modelBuilder.Configurations.Add(new StoreMap());  
    184.             modelBuilder.Configurations.Add(new vEmployeeMap());  
    185.             modelBuilder.Configurations.Add(new vEmployeeDepartmentMap());  
    186.             modelBuilder.Configurations.Add(new vEmployeeDepartmentHistoryMap());  
    187.             modelBuilder.Configurations.Add(new vJobCandidateMap());  
    188.             modelBuilder.Configurations.Add(new vJobCandidateEducationMap());  
    189.             modelBuilder.Configurations.Add(new vJobCandidateEmploymentMap());  
    190.             modelBuilder.Configurations.Add(new vAdditionalContactInfoMap());  
    191.             modelBuilder.Configurations.Add(new vStateProvinceCountryRegionMap());  
    192.             modelBuilder.Configurations.Add(new vProductAndDescriptionMap());  
    193.             modelBuilder.Configurations.Add(new vProductModelCatalogDescriptionMap());  
    194.             modelBuilder.Configurations.Add(new vProductModelInstructionMap());  
    195.             modelBuilder.Configurations.Add(new vVendorWithAddressMap());  
    196.             modelBuilder.Configurations.Add(new vVendorWithContactMap());  
    197.             modelBuilder.Configurations.Add(new vIndividualCustomerMap());  
    198.             modelBuilder.Configurations.Add(new vPersonDemographicMap());  
    199.             modelBuilder.Configurations.Add(new vSalesPersonMap());  
    200.             modelBuilder.Configurations.Add(new vSalesPersonSalesByFiscalYearMap());  
    201.             modelBuilder.Configurations.Add(new vStoreWithAddressMap());  
    202.             modelBuilder.Configurations.Add(new vStoreWithContactMap());  
    203.             modelBuilder.Configurations.Add(new vStoreWithDemographicMap());  
    204.         }  
    205.     }  
    206. }  
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;
    using EFPowerTools.Models.Mapping;
    
    namespace EFPowerTools.Models
    {
        public partial class AdventureWorksContext : DbContext
        {
            static AdventureWorksContext()
            {
                Database.SetInitializer<AdventureWorksContext>(null);
            }
    
            public AdventureWorksContext()
                : base("Name=AdventureWorksContext")
            {
            }
    
            public DbSet<AWBuildVersion> AWBuildVersions { get; set; }
            public DbSet<DatabaseLog> DatabaseLogs { get; set; }
            public DbSet<ErrorLog> ErrorLogs { get; set; }
            public DbSet<OrderDetail> OrderDetails { get; set; }
            public DbSet<Order> Orders { get; set; }
            public DbSet<Department> Departments { get; set; }
            public DbSet<Employee> Employees { get; set; }
            public DbSet<EmployeeDepartmentHistory> EmployeeDepartmentHistories { get; set; }
            public DbSet<EmployeePayHistory> EmployeePayHistories { get; set; }
            public DbSet<JobCandidate> JobCandidates { get; set; }
            public DbSet<Shift> Shifts { get; set; }
            public DbSet<Address> Addresses { get; set; }
            public DbSet<AddressType> AddressTypes { get; set; }
            public DbSet<BusinessEntity> BusinessEntities { get; set; }
            public DbSet<BusinessEntityAddress> BusinessEntityAddresses { get; set; }
            public DbSet<BusinessEntityContact> BusinessEntityContacts { get; set; }
            public DbSet<ContactType> ContactTypes { get; set; }
            public DbSet<CountryRegion> CountryRegions { get; set; }
            public DbSet<EmailAddress> EmailAddresses { get; set; }
            public DbSet<Password> Passwords { get; set; }
            public DbSet<Person> People { get; set; }
            public DbSet<PersonPhone> PersonPhones { get; set; }
            public DbSet<PhoneNumberType> PhoneNumberTypes { get; set; }
            public DbSet<StateProvince> StateProvinces { get; set; }
            public DbSet<BillOfMaterial> BillOfMaterials { get; set; }
            public DbSet<Culture> Cultures { get; set; }
            public DbSet<Illustration> Illustrations { get; set; }
            public DbSet<Location> Locations { get; set; }
            public DbSet<Product> Products { get; set; }
            public DbSet<ProductCategory> ProductCategories { get; set; }
            public DbSet<ProductCostHistory> ProductCostHistories { get; set; }
            public DbSet<ProductDescription> ProductDescriptions { get; set; }
            public DbSet<ProductInventory> ProductInventories { get; set; }
            public DbSet<ProductListPriceHistory> ProductListPriceHistories { get; set; }
            public DbSet<ProductModel> ProductModels { get; set; }
            public DbSet<ProductModelIllustration> ProductModelIllustrations { get; set; }
            public DbSet<ProductModelProductDescriptionCulture> ProductModelProductDescriptionCultures { get; set; }
            public DbSet<ProductPhoto> ProductPhotoes { get; set; }
            public DbSet<ProductProductPhoto> ProductProductPhotoes { get; set; }
            public DbSet<ProductReview> ProductReviews { get; set; }
            public DbSet<ProductSubcategory> ProductSubcategories { get; set; }
            public DbSet<ScrapReason> ScrapReasons { get; set; }
            public DbSet<TransactionHistory> TransactionHistories { get; set; }
            public DbSet<TransactionHistoryArchive> TransactionHistoryArchives { get; set; }
            public DbSet<UnitMeasure> UnitMeasures { get; set; }
            public DbSet<WorkOrder> WorkOrders { get; set; }
            public DbSet<WorkOrderRouting> WorkOrderRoutings { get; set; }
            public DbSet<ProductVendor> ProductVendors { get; set; }
            public DbSet<PurchaseOrderDetail> PurchaseOrderDetails { get; set; }
            public DbSet<PurchaseOrderHeader> PurchaseOrderHeaders { get; set; }
            public DbSet<ShipMethod> ShipMethods { get; set; }
            public DbSet<Vendor> Vendors { get; set; }
            public DbSet<CountryRegionCurrency> CountryRegionCurrencies { get; set; }
            public DbSet<CreditCard> CreditCards { get; set; }
            public DbSet<Currency> Currencies { get; set; }
            public DbSet<CurrencyRate> CurrencyRates { get; set; }
            public DbSet<Customer> Customers { get; set; }
            public DbSet<PersonCreditCard> PersonCreditCards { get; set; }
            public DbSet<SalesOrderDetail> SalesOrderDetails { get; set; }
            public DbSet<SalesOrderHeader> SalesOrderHeaders { get; set; }
            public DbSet<SalesOrderHeaderSalesReason> SalesOrderHeaderSalesReasons { get; set; }
            public DbSet<SalesPerson> SalesPersons { get; set; }
            public DbSet<SalesPersonQuotaHistory> SalesPersonQuotaHistories { get; set; }
            public DbSet<SalesReason> SalesReasons { get; set; }
            public DbSet<SalesTaxRate> SalesTaxRates { get; set; }
            public DbSet<SalesTerritory> SalesTerritories { get; set; }
            public DbSet<SalesTerritoryHistory> SalesTerritoryHistories { get; set; }
            public DbSet<ShoppingCartItem> ShoppingCartItems { get; set; }
            public DbSet<SpecialOffer> SpecialOffers { get; set; }
            public DbSet<SpecialOfferProduct> SpecialOfferProducts { get; set; }
            public DbSet<Store> Stores { get; set; }
            public DbSet<vEmployee> vEmployees { get; set; }
            public DbSet<vEmployeeDepartment> vEmployeeDepartments { get; set; }
            public DbSet<vEmployeeDepartmentHistory> vEmployeeDepartmentHistories { get; set; }
            public DbSet<vJobCandidate> vJobCandidates { get; set; }
            public DbSet<vJobCandidateEducation> vJobCandidateEducations { get; set; }
            public DbSet<vJobCandidateEmployment> vJobCandidateEmployments { get; set; }
            public DbSet<vAdditionalContactInfo> vAdditionalContactInfoes { get; set; }
            public DbSet<vStateProvinceCountryRegion> vStateProvinceCountryRegions { get; set; }
            public DbSet<vProductAndDescription> vProductAndDescriptions { get; set; }
            public DbSet<vProductModelCatalogDescription> vProductModelCatalogDescriptions { get; set; }
            public DbSet<vProductModelInstruction> vProductModelInstructions { get; set; }
            public DbSet<vVendorWithAddress> vVendorWithAddresses { get; set; }
            public DbSet<vVendorWithContact> vVendorWithContacts { get; set; }
            public DbSet<vIndividualCustomer> vIndividualCustomers { get; set; }
            public DbSet<vPersonDemographic> vPersonDemographics { get; set; }
            public DbSet<vSalesPerson> vSalesPersons { get; set; }
            public DbSet<vSalesPersonSalesByFiscalYear> vSalesPersonSalesByFiscalYears { get; set; }
            public DbSet<vStoreWithAddress> vStoreWithAddresses { get; set; }
            public DbSet<vStoreWithContact> vStoreWithContacts { get; set; }
            public DbSet<vStoreWithDemographic> vStoreWithDemographics { get; set; }
    
            protected override void OnModelCreating(DbModelBuilder modelBuilder)
            {
                modelBuilder.Configurations.Add(new AWBuildVersionMap());
                modelBuilder.Configurations.Add(new DatabaseLogMap());
                modelBuilder.Configurations.Add(new ErrorLogMap());
                modelBuilder.Configurations.Add(new OrderDetailMap());
                modelBuilder.Configurations.Add(new OrderMap());
                modelBuilder.Configurations.Add(new DepartmentMap());
                modelBuilder.Configurations.Add(new EmployeeMap());
                modelBuilder.Configurations.Add(new EmployeeDepartmentHistoryMap());
                modelBuilder.Configurations.Add(new EmployeePayHistoryMap());
                modelBuilder.Configurations.Add(new JobCandidateMap());
                modelBuilder.Configurations.Add(new ShiftMap());
                modelBuilder.Configurations.Add(new AddressMap());
                modelBuilder.Configurations.Add(new AddressTypeMap());
                modelBuilder.Configurations.Add(new BusinessEntityMap());
                modelBuilder.Configurations.Add(new BusinessEntityAddressMap());
                modelBuilder.Configurations.Add(new BusinessEntityContactMap());
                modelBuilder.Configurations.Add(new ContactTypeMap());
                modelBuilder.Configurations.Add(new CountryRegionMap());
                modelBuilder.Configurations.Add(new EmailAddressMap());
                modelBuilder.Configurations.Add(new PasswordMap());
                modelBuilder.Configurations.Add(new PersonMap());
                modelBuilder.Configurations.Add(new PersonPhoneMap());
                modelBuilder.Configurations.Add(new PhoneNumberTypeMap());
                modelBuilder.Configurations.Add(new StateProvinceMap());
                modelBuilder.Configurations.Add(new BillOfMaterialMap());
                modelBuilder.Configurations.Add(new CultureMap());
                modelBuilder.Configurations.Add(new IllustrationMap());
                modelBuilder.Configurations.Add(new LocationMap());
                modelBuilder.Configurations.Add(new ProductMap());
                modelBuilder.Configurations.Add(new ProductCategoryMap());
                modelBuilder.Configurations.Add(new ProductCostHistoryMap());
                modelBuilder.Configurations.Add(new ProductDescriptionMap());
                modelBuilder.Configurations.Add(new ProductInventoryMap());
                modelBuilder.Configurations.Add(new ProductListPriceHistoryMap());
                modelBuilder.Configurations.Add(new ProductModelMap());
                modelBuilder.Configurations.Add(new ProductModelIllustrationMap());
                modelBuilder.Configurations.Add(new ProductModelProductDescriptionCultureMap());
                modelBuilder.Configurations.Add(new ProductPhotoMap());
                modelBuilder.Configurations.Add(new ProductProductPhotoMap());
                modelBuilder.Configurations.Add(new ProductReviewMap());
                modelBuilder.Configurations.Add(new ProductSubcategoryMap());
                modelBuilder.Configurations.Add(new ScrapReasonMap());
                modelBuilder.Configurations.Add(new TransactionHistoryMap());
                modelBuilder.Configurations.Add(new TransactionHistoryArchiveMap());
                modelBuilder.Configurations.Add(new UnitMeasureMap());
                modelBuilder.Configurations.Add(new WorkOrderMap());
                modelBuilder.Configurations.Add(new WorkOrderRoutingMap());
                modelBuilder.Configurations.Add(new ProductVendorMap());
                modelBuilder.Configurations.Add(new PurchaseOrderDetailMap());
                modelBuilder.Configurations.Add(new PurchaseOrderHeaderMap());
                modelBuilder.Configurations.Add(new ShipMethodMap());
                modelBuilder.Configurations.Add(new VendorMap());
                modelBuilder.Configurations.Add(new CountryRegionCurrencyMap());
                modelBuilder.Configurations.Add(new CreditCardMap());
                modelBuilder.Configurations.Add(new CurrencyMap());
                modelBuilder.Configurations.Add(new CurrencyRateMap());
                modelBuilder.Configurations.Add(new CustomerMap());
                modelBuilder.Configurations.Add(new PersonCreditCardMap());
                modelBuilder.Configurations.Add(new SalesOrderDetailMap());
                modelBuilder.Configurations.Add(new SalesOrderHeaderMap());
                modelBuilder.Configurations.Add(new SalesOrderHeaderSalesReasonMap());
                modelBuilder.Configurations.Add(new SalesPersonMap());
                modelBuilder.Configurations.Add(new SalesPersonQuotaHistoryMap());
                modelBuilder.Configurations.Add(new SalesReasonMap());
                modelBuilder.Configurations.Add(new SalesTaxRateMap());
                modelBuilder.Configurations.Add(new SalesTerritoryMap());
                modelBuilder.Configurations.Add(new SalesTerritoryHistoryMap());
                modelBuilder.Configurations.Add(new ShoppingCartItemMap());
                modelBuilder.Configurations.Add(new SpecialOfferMap());
                modelBuilder.Configurations.Add(new SpecialOfferProductMap());
                modelBuilder.Configurations.Add(new StoreMap());
                modelBuilder.Configurations.Add(new vEmployeeMap());
                modelBuilder.Configurations.Add(new vEmployeeDepartmentMap());
                modelBuilder.Configurations.Add(new vEmployeeDepartmentHistoryMap());
                modelBuilder.Configurations.Add(new vJobCandidateMap());
                modelBuilder.Configurations.Add(new vJobCandidateEducationMap());
                modelBuilder.Configurations.Add(new vJobCandidateEmploymentMap());
                modelBuilder.Configurations.Add(new vAdditionalContactInfoMap());
                modelBuilder.Configurations.Add(new vStateProvinceCountryRegionMap());
                modelBuilder.Configurations.Add(new vProductAndDescriptionMap());
                modelBuilder.Configurations.Add(new vProductModelCatalogDescriptionMap());
                modelBuilder.Configurations.Add(new vProductModelInstructionMap());
                modelBuilder.Configurations.Add(new vVendorWithAddressMap());
                modelBuilder.Configurations.Add(new vVendorWithContactMap());
                modelBuilder.Configurations.Add(new vIndividualCustomerMap());
                modelBuilder.Configurations.Add(new vPersonDemographicMap());
                modelBuilder.Configurations.Add(new vSalesPersonMap());
                modelBuilder.Configurations.Add(new vSalesPersonSalesByFiscalYearMap());
                modelBuilder.Configurations.Add(new vStoreWithAddressMap());
                modelBuilder.Configurations.Add(new vStoreWithContactMap());
                modelBuilder.Configurations.Add(new vStoreWithDemographicMap());
            }
        }
    }
    

    在项目中我们还可以看到Entity Framework Power Tools自动创建了一个Models文件夹,这里除了“AdventureWorksContext”类还有所有的数据类。在Models文件夹下还有一个“Mapping”文件夹,这里放了数据类与数据库的映射配置类,可以看出Entity Framework Power Tools通过fluent API的方式进行映射细节配置(目前Entity Framework Power Tools还不支持Data Annotations方式),关于配置类的具体细节我们这里暂不进行详细介绍。

    下面我们进行数据查询:

    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Text;  
    5. using System.Threading.Tasks;  
    6. using EFPowerTools.Models;  
    7.   
    8. namespace EFPowerTools  
    9. {  
    10.     class Program  
    11.     {  
    12.         static void Main(string[] args)  
    13.         {  
    14.             using (var db = new AdventureWorksContext())  
    15.             {  
    16.                 var persons = db.People.Where(p => p.LastName == "Stevens").OrderBy(p=>p.FirstName);  
    17.                 foreach(var p in persons)  
    18.                 {  
    19.                     Console.WriteLine("FirstName:{0},LastName:{1}", p.FirstName, p.LastName);  
    20.                 }  
    21.             }  
    22.         }  
    23.     }  
    24. }  
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using EFPowerTools.Models;
    
    namespace EFPowerTools
    {
        class Program
        {
            static void Main(string[] args)
            {
                using (var db = new AdventureWorksContext())
                {
                    var persons = db.People.Where(p => p.LastName == "Stevens").OrderBy(p=>p.FirstName);
                    foreach(var p in persons)
                    {
                        Console.WriteLine("FirstName:{0},LastName:{1}", p.FirstName, p.LastName);
                    }
                }
            }
        }
    }
    

    查询结果:

    自定义模板

    事实上Entity Framework Power Tools的功能还远不止这些,例如我们上面谈到Entity Framework Power Tools使用fluent API进行映射配置,而通常情况下开发人员更喜欢使用Data Annotations方式进行映射约定,那么此时你就可以选择配置自己的模板。

    在项目上右键选择Entity Frmaework->Customize Reverse Engineer Templates,此时会看到项目中添加了一个“CodeTemplates”文件夹,里面存放了Entity Framework Power Tools用于生产相关类文件的T4模板(对于不了解T4模板引擎的朋友可以点击这里Lowering the Barriers to Code Generation with T4),如果此时再使用Entity Framework Power Tools进行Code First反向工程操作将使用当前这个文件夹中的模板进行生成。接下来看一下如何进行模板自定义。

    首先让我们打开Mapping.tt文件,这个文件主要用户生成配置类,在Entity Framework Power Tools默认生成的代码中通过fluent API进行表名和数据类名以及属性名同列名的对应配置,例如下面的代码:

    下面让我们修改一下Mapping.tt文件,去掉上面的约束,而改用Data Annotations方式进行约定。首先去掉下图中选择的代码,此时生成的映射类中就不再出现上图中选择的代码部分:

    然后我们需要修改Entity.tt模板,将数据库中的表和列的映射声明到数据类上。先让我们将数据类和表做对应,这需要在数据类上添加“Table”声明,标记出表名和架构名(EF默认会使用dbo架构),在如图位置添加如下代码:

    1. <#   
    2.         var tableName = (string)efHost.TableSet.MetadataProperties["Table"].Value ?? efHost.TableSet.Name;   
    3.         var conventionTableName = System.Data.Entity.Design.PluralizationServices.PluralizationService   
    4.                 .CreateService(new CultureInfo("en"))   
    5.                 .Pluralize(efHost.EntityType.Name);  
    6.   
    7.         var schemaName = (string)efHost.TableSet.MetadataProperties["Schema"].Value;   
    8.         schemaName = string.IsNullOrWhiteSpace(schemaName)   
    9.                 ? "dbo"   
    10.                 : schemaName;  
    11.   
    12.         if(schemaName != "dbo" || conventionTableName != tableName)   
    13.         {   
    14. #>   
    15.     [Table("<#= tableName #>", Schema="<#= schemaName #>")]   
    16. <#   
    17.         }  
    18.  
    19. #>   
    <# 
            var tableName = (string)efHost.TableSet.MetadataProperties["Table"].Value ?? efHost.TableSet.Name; 
            var conventionTableName = System.Data.Entity.Design.PluralizationServices.PluralizationService 
                    .CreateService(new CultureInfo("en")) 
                    .Pluralize(efHost.EntityType.Name);
    
            var schemaName = (string)efHost.TableSet.MetadataProperties["Schema"].Value; 
            schemaName = string.IsNullOrWhiteSpace(schemaName) 
                    ? "dbo" 
                    : schemaName;
    
            if(schemaName != "dbo" || conventionTableName != tableName) 
            { 
    #> 
        [Table("<#= tableName #>", Schema="<#= schemaName #>")] 
    <# 
            }
    
    #> 

    这段代码主要处理逻辑是:当架构不是“dbo”或者表名的复数形式同表名不同时添加“Table”标记声明。之所以添加判断是因为EF的默认使用“dbo”架构并且EF在操作表的时候默认将数据类的复数形式作为表名。

    接下来添加列标记声明,在如图位置添加如下代码即可:

    var columnName = efHost.PropertyToColumnMappings[property].Name; if(code.Escape(property) != columnName) { #> [Column("<#= columnName #>")] <# }

    这里只是简单的对列名和编码后的列名进行比较,不同则添加列标记,否则不添加(EF默认认为数据类属性名和表的列名相同)。

    由于刚才添加的标记属性类在“System.ComponentModel.DataAnnotations.Schema” 命名空间下,因此最后还需要在模板头部添加该命名空间:

     

    1. <#   
    2.        if (efHost.EntityFrameworkVersion >= new Version(4, 4))   
    3.         {   
    4. #>   
    5. using System.ComponentModel.DataAnnotations.Schema;   
    6. <#   
    7.         }   
    8.         else   
    9.         {   
    10. #>   
    11. using System.ComponentModel.DataAnnotations;   
    12. <#   
    13.         }   
    14. #>  
    <# 
           if (efHost.EntityFrameworkVersion >= new Version(4, 4)) 
            { 
    #> 
    using System.ComponentModel.DataAnnotations.Schema; 
    <# 
            } 
            else 
            { 
    #> 
    using System.ComponentModel.DataAnnotations; 
    <# 
            } 
    #>

    由于之前的EF版本中“Table”和“Column”类不在“System.ComponentModel.DataAnnotations.Schema”命名空间而是在 “System.ComponentModel.DataAnnotations”命名空间中,因此这里我们还需要添加一个判断。

    今天的内容先到此为止,关于如何使用fluent API及Data Annotations定义配置类来进行更多的映射控制请关注后面的文章。

  • 相关阅读:
    ps+div+css打造蓝色后台login页面实现,ps切片,浏览器兼容
    mysql 常用命令与问题
    struts2 笔记
    hibernate在eclipse的逆向工程生成hbm.xml和bean类
    struts2 checkbox 传值的用法
    css 背景渐变,圆角,阴影用法与兼容
    Firefox 插件 JSview下载
    Spark插件开发完全入门手册,多级组织架构初步(原创) CVT
    Java 动态代理机制分析及扩展,第 2 部分(转) CVT
    Windows 2012服务器建立域控(AD DS)详解(转) CVT
  • 原文地址:https://www.cnblogs.com/springwind268/p/4465951.html
Copyright © 2020-2023  润新知