在前面的文章中我们提到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”的数据库连接串:
xml version="1.0" encoding="utf-8"?> <configuration> <configSections> <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”数据库连接:
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( null); } public AdventureWorksContext() : base("Name=AdventureWorksContext") { } public DbSetAWBuildVersions { get; set; } public DbSetDatabaseLogs { get; set; } public DbSetErrorLogs { get; set; } public DbSetOrderDetails { get; set; } public DbSetOrders { get; set; } public DbSetDepartments { get; set; } public DbSetEmployees { get; set; } public DbSetEmployeeDepartmentHistories { get; set; } public DbSetEmployeePayHistories { get; set; } public DbSetJobCandidates { get; set; } public DbSetShifts { get; set; } public DbSet Addresses { get; set; } public DbSetAddressTypes { get; set; } public DbSetBusinessEntities { get; set; } public DbSetBusinessEntityAddresses { get; set; } public DbSetBusinessEntityContacts { get; set; } public DbSetContactTypes { get; set; } public DbSetCountryRegions { get; set; } public DbSetEmailAddresses { get; set; } public DbSetPasswords { get; set; } public DbSetPeople { get; set; } public DbSetPersonPhones { get; set; } public DbSetPhoneNumberTypes { get; set; } public DbSetStateProvinces { get; set; } public DbSetBillOfMaterials { get; set; } public DbSetCultures { get; set; } public DbSetIllustrations { get; set; } public DbSetLocations { get; set; } public DbSetProducts { get; set; } public DbSetProductCategories { get; set; } public DbSetProductCostHistories { get; set; } public DbSetProductDescriptions { get; set; } public DbSetProductInventories { get; set; } public DbSetProductListPriceHistories { get; set; } public DbSetProductModels { get; set; } public DbSetProductModelIllustrations { get; set; } public DbSetProductModelProductDescriptionCultures { get; set; } public DbSetProductPhotoes { get; set; } public DbSetProductProductPhotoes { get; set; } public DbSetProductReviews { get; set; } public DbSetProductSubcategories { get; set; } public DbSetScrapReasons { get; set; } public DbSetTransactionHistories { get; set; } public DbSetTransactionHistoryArchives { get; set; } public DbSetUnitMeasures { get; set; } public DbSetWorkOrders { get; set; } public DbSetWorkOrderRoutings { get; set; } public DbSetProductVendors { get; set; } public DbSetPurchaseOrderDetails { get; set; } public DbSetPurchaseOrderHeaders { get; set; } public DbSetShipMethods { get; set; } public DbSetVendors { get; set; } public DbSetCountryRegionCurrencies { get; set; } public DbSetCreditCards { get; set; } public DbSetCurrencies { get; set; } public DbSetCurrencyRates { get; set; } public DbSetCustomers { get; set; } public DbSetPersonCreditCards { get; set; } public DbSetSalesOrderDetails { get; set; } public DbSetSalesOrderHeaders { get; set; } public DbSetSalesOrderHeaderSalesReasons { get; set; } public DbSetSalesPersons { get; set; } public DbSetSalesPersonQuotaHistories { get; set; } public DbSetSalesReasons { get; set; } public DbSetSalesTaxRates { get; set; } public DbSetSalesTerritories { get; set; } public DbSetSalesTerritoryHistories { get; set; } public DbSetShoppingCartItems { get; set; } public DbSetSpecialOffers { get; set; } public DbSetSpecialOfferProducts { get; set; } public DbSetStores { get; set; } public DbSetvEmployees { get; set; } public DbSetvEmployeeDepartments { get; set; } public DbSetvEmployeeDepartmentHistories { get; set; } public DbSetvJobCandidates { get; set; } public DbSetvJobCandidateEducations { get; set; } public DbSetvJobCandidateEmployments { get; set; } public DbSetvAdditionalContactInfoes { get; set; } public DbSetvStateProvinceCountryRegions { get; set; } public DbSetvProductAndDescriptions { get; set; } public DbSetvProductModelCatalogDescriptions { get; set; } public DbSetvProductModelInstructions { get; set; } public DbSetvVendorWithAddresses { get; set; } public DbSetvVendorWithContacts { get; set; } public DbSetvIndividualCustomers { get; set; } public DbSetvPersonDemographics { get; set; } public DbSetvSalesPersons { get; set; } public DbSetvSalesPersonSalesByFiscalYears { get; set; } public DbSetvStoreWithAddresses { get; set; } public DbSetvStoreWithContacts { get; set; } public DbSetvStoreWithDemographics { 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方式),关于配置类的具体细节我们这里暂不进行详细介绍。
下面我们进行数据查询:
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架构),在如图位置添加如下代码:
<#
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” 命名空间下,因此最后还需要在模板头部添加该命名空间:
<#
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定义配置类来进行更多的映射控制请关注后面的文章。