【转】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”数据库)。


注意:如果使用“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”的数据库连接串:

[html] view plaincopyprint?

  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”数据库连接:

[csharp] view plaincopyprint?

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

下面我们进行数据查询:

[csharp] view plaincopyprint?

  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. namespace EFPowerTools
  8. {
  9. class Program
  10. {
  11. static void Main(string[] args)
  12. {
  13. using (var db = new AdventureWorksContext())
  14. {
  15. var persons = db.People.Where(p => p.LastName == "Stevens").OrderBy(p=>p.FirstName);
  16. foreach(var p in persons)
  17. {
  18. Console.WriteLine("FirstName:{0},LastName:{1}", p.FirstName, p.LastName);
  19. }
  20. }
  21. }
  22. }
  23. }
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架构),在如图位置添加如下代码:

[csharp] view plaincopyprint?

  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. var schemaName = (string)efHost.TableSet.MetadataProperties["Schema"].Value;
  7. schemaName = string.IsNullOrWhiteSpace(schemaName)
  8. ? "dbo"
  9. : schemaName;
  10. if(schemaName != "dbo" || conventionTableName != tableName)
  11. {
  12. #>
  13. [Table("<#= tableName #>", Schema="<#= schemaName #>")]
  14. <#
  15. }
  16. #>
<#
        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” 命名空间下,因此最后还需要在模板头部添加该命名空间:

[csharp] view plaincopyprint?

  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定义配置类来进行更多的映射控制请关注后面的文章。

时间: 2024-10-10 00:26:40

【转】Entity Framework 5.0系列之自动生成Code First代码的相关文章

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反向工程工具).

Entity Framework 5.0系列之EF概览

概述 在开发面向数据的软件时我们常常为了解决业务问题实体.关系和逻辑构建模型而费尽心机,ORM的产生为我们提供了一种优雅的解决方案.ADO.NET Entity Framework是.NET开发中一种由ADO.NET驱动的ORM框架,使用Entity Framework开发人员可以不必考虑数据的基础数据表和列,在处理数据时能够以更高的抽象级别进行工作,并能够以相对传统开发编写更少的代码来创建和维护应用程序. 我们知道面向对象的编程与数据存储系统的交换提出了一个难题:类结构通常同关系数据表组织结构

Entity Framework 5.0系列之约定配置

Code First之所以能够让开发人员以一种更加高效.灵活的方式进行数据操作有一个重要的原因在于它的约定配置.现在软件开发越来复杂,大家也都试图将软件设计的越来越灵活,很多内容我们都希望是可配置的,但是过多的配置也会带来很大的工作量,解决这个问题的方法就是约定.对于一些简单的,不太可能经常变化的内容我们以一种约定的方式进行设计.使用过其他ORM框架的朋友可能知道一般ORM都有对应的映射配置文件(一般是一个Xml文件),但是EF并没有.在EF中是以一种约定的方式进行表.列同实体类进行映射的,与此

【转】Entity Framework 5.0系列之约定配置

Code First之所以能够让开发人员以一种更加高效.灵活的方式进行数据操作有一个重要的原因在于它的约定配置.现在软件开发越来复杂,大家也都试图将软件设计的越来越灵活,很多内容我们都希望是可配置的,但是过多的配置也会带来很大的工作量,解决这个问题的方法就是约定.对于一些简单的,不太可能经常变化的内容我们以一种约定的方式进行设计.使用过其他ORM框架的朋友可能知道一般ORM都有对应的映射配置文件(一般是一个Xml文件),但是EF并没有.在EF中是以一种约定的方式进行表.列同实体类进行映射的,与此

【转】Entity Framework技术导游系列开篇与热身

转自:http://blog.csdn.net/bitfan/article/details/12779517 Entity Framework走马观花 之 把握全局 ========================================= 这是一个系列文章 上一篇<Entity Framework技术导游系列开篇与热身 > ========================================= 在深入学习某项技术之前,应该努力形成对此技术的总体印象,并了解其基本原理,本

初次开发 ASP.NET vNext 续篇:云优化的概念、Entity Framework 7.0、目前性能还不够好

继续上一篇<开发 ASP.NET vNext 初步总结(使用Visual Studio 2014 CTP1)>之后, 关于云优化和版本控制: 我本想做一下MAC和LINUX的self-host测试,但是官方说运行环境的MONO版本至少需要3.4.1,我去年买了个表,至本文发布为止,你让我下地狱去找3.4.1吗,硬着头皮用3.4.0搞了一晚上,MAC一直停留在 httpapi.dll出错,Ubuntu Server 12.0.4 是不认其中的几个DLL包,具体哪几个也忘了,过段时间有了稳定版本再

Entity Framework 5.0 Code First全面学习

目录(?)[+] 不贴图片了,太累. Code First 约定 借助 CodeFirst,可通过使用 C# 或Visual Basic .NET 类来描述模型.模型的基本形状可通过约定来检测.约定是规则集,用于在使用 Code First 时基于类定义自动配置概念模型.约定是在 System.Data.Entity.ModelConfiguration.Conventions 命名空间中定义的. 可通过使用数据注释或Fluent API 进一步配置模型.优先级是通过 Fluent API 进行

Entity Framework 5.0 Code First全面学习 (转)

原文地址:感谢原文作者 http://blog.csdn.net/gentle_wolf/article/details/14004345 不贴图片了,太累. Code First 约定 借助 CodeFirst,可通过使用 C# 或Visual Basic .NET 类来描述模型.模型的基本形状可通过约定来检测.约定是规则集,用于在使用 Code First 时基于类定义自动配置概念模型.约定是在 System.Data.Entity.ModelConfiguration.Convention

Entity Framework 6 开发系列 目录

2014 年开始接触 Entity Framework 6 也快两年,用它已经沉淀了一个成熟架构,也用来开发了不少大大小小的产品和项目,直到这段时间,才真正有时间来回顾,重新学习它,为让大家更加了解Entity Framework 6,以及想把这两年中,开发过程中碰到的种种问题,跟大家分享,特此想做一个Entity Framework 6 开发系列的计划 第一篇:Entity Framework 简介 第二篇:Entity Framework CodeFirst & Model 映射 第三篇:E