Generating a model from an existing database
文章推薦指數: 80 %
You use the DbContext Scaffold command to generate the model. The command has two required arguments - a connection string and a provider. Togglenavigation LearnEntityFrameworkCore YourguidetousingthelatestversionofMicrosoft'sObjectRelationalMapper EFCoreNewsletter Home HowToGetEFCore DbContext AddingData ModifyingData DeletingData ChangeTracker DbSet QueryingData AddingData ModifyingData DeletingData Model FromExistingDatabase ShadowProperties Relationships ManagingOneToManyRelationships ReferentialConstraintActionOptions Conventions OneToManyRelationship OneToOneRelationship ManyToManyRelationship Configuration DataAnnotationAttributes ColumnAttribute ComplexTypeAttribute ConcurrencyCheckAttribute DatabaseGeneratedAttribute ForeignKeyAttribute IndexAttribute InversePropertyAttribute KeyAttribute MaxLengthAttribute NotMappedAttribute RequiredAttribute StringLengthAttribute TableAttribute TimestampAttribute FluentApi ModelConfiguration PropertyConfiguration HasAlternatekeyMethod HasColumnNameMethod HasColumnTypeMethod HasComputedColumnSqlMethod HasConstraintNameMethod HasDataMethod HasDefaultValueMethod HasDefaultValueSqlMethod HasDiscriminatorMethod HasFieldMethod HasForeignKeyMethod HasIndexMethod HasKeyMethod HasManyMethod HasMaxLengthMethod HasOneMethod HasQueryFilterMethod HasValueMethod Has/WithPattern IgnoreMethod IsConcurrencyTokenMethod IsRequiredMethod IsRowVersionMethod OnDeleteMethod ToTableMethod ToViewMethod TypeConfiguration ValueGeneratedNeverMethod ValueGeneratedOnAddMethod ValueGeneratedOnAddOrUpdateMethod WithManyMethod WithOneMethod OneToManyRelationshipConfiguration OneToOneRelationshipConfiguration ManyToManyRelationshipConfiguration ConnectionStrings Inheritance TablePerHierarchy Concurrency Migrations ModelSnapshot SeedingData Commands CLICommands PMCCommands Walkthoughs ASP.NETCoreMVCApplication .NETCoreConsoleApplication UsingAnExistingDatabase RawSQL DatabaseFirstAndEntityFrameworkCore QueryTypes LazyLoading FastestEntityFrameworkExtensions BulkInsert BulkDelete BulkUpdate BulkMerge Startingwithanexistingdatabase PreviousversionsofEntityFrameworksupportaDatabase-Firstapproachtodevelopment.Inthisapproach,youreverse-engineeramodelfromanexistingdatabase,resultinginthegenerationofanEDMXfilethatcontainsthemodeldefinitionandmappinginformation.ToolingsupportfortheEDMXfilewasdroppedinEntityFrameworkCoreinfavourofusingcommandstoreverse-engineerclassfilesforthemodelfromanexistingdatabaseschema.ThisapproachisknownasCodeFirsttoanexistingdatabase. CommandLineInterface ThefollowingexampleillustrateshowtodousecodefirsttotogenerateamodelfromaSQLServerdatabaseinanewconsoleapplicationusingtheCLItools. First,createafolderfortheproject: >mkdirEFCoreScaffoldexample Thennavigatetoit: >cdEFCoreScaffoldExample Thencreateanewproject: >dotnetnewconsole AddtheEntityFrameworkCoreandToolspackagestotheproject: >dotnetaddpackageMicrosoft.EntityFrameworkCore.SqlServer >dotnetaddpackageMicrosoft.EntityFrameworkCore.Design ThefirstpackageistheEFCoreproviderforSQLServer.ThesecondpackagecontainstheEntityFrameworkCorecommands.BothofthesepackagesarerequiredforanyEntityFrameworkCoreapplicationthattargetsSQLServer. Testtoseeifefcommandsareavailabletoyou: dotnetef-h ThisshouldresultintheinitialhelpfortheEFtoolsbeingdisplayed: Ifyougeterrorslikethis: Couldnotexecutebecausethespecifiedcommandorfilewasnotfound. Possiblereasonsforthisinclude: *Youmisspelledabuilt-indotnetcommand. *Youintendedtoexecutea.NETCoreprogram,butdotnet-efdoesnotexist. *Youintendedtorunaglobaltool,butadotnet-prefixedexecutablewiththisnamecouldnotbefoundonthePATH. tryinstallingtheEFCoretoolbyexecutingthefollowingcommand: dotnettoolinstall--globaldotnet-ef YouusetheDbContextScaffoldcommandtogeneratethemodel.Thecommandhastworequiredarguments-aconnectionstringandaprovider.Theconnectionstringwilldependonyourenvironmentanddatabaseprovider.TheproviderargumentistheEntityFrameworkproviderforyourchosendatabase.ThisexampleusestheAdventureWorkssampledatabaseforSQLserverprovidedbyMicrosoft. >dotnetefdbcontextscaffold"Server=.\;Database=AdventureWorksLT2012;Trusted_Connection=True;"Microsoft.EntityFrameworkCore.SqlServer-oModel Onceyouhaveexecutedthecommand,youwillseethatafoldernamedModelhasbeencreatedintheprojectfolder,containingacollectionofclassfilesrepresentingtheentitiesinadditiontoafilefortheDbContextclass: The-ooption(oralternatively--output-dir)specifiesthedirectorywheretheclassfileswillbegenerated.Ifitisomitted,theclassfileswillbegeneratedintheprojectdirectory(wherethe.csprojfileislocated). TheDbContextclasswilltakethenameofthedatabaseplus"Context",Youcanoverridethisusingthe-cor--contextoptione.g. >dotnetefdbcontextscaffold"Server=.\;Database=AdventureWorksLT2012;Trusted_Connection=True;"Microsoft.EntityFrameworkCore.SqlServer-oModel-c"AdventureContext" ModelConfiguration TheresultingmodelisconfiguredusingtheFluentAPIbydefault,whichistherecommendedapproach.Theconfigurationsareplacedinthegeneratedcontext'sOnModelCreatingmethod.However,ifyouprefertouseDataAnnotationsforconfiguration,youcanusethe-dor--data-annotationsswitch: dotnetefdbcontextscaffold"Server=.\;Database=AdventureWorksLT2012;Trusted_Connection=True;"Microsoft.EntityFrameworkCore.SqlServer-d SinceDataAnnotationsonlycoverasubsetofconfigurationoptions,youarelikelytofindthattheFluentAPIhasalsobeenusedtoconfigurethemodel. UpdatingtheModel Therecommendedapproachtokeepingchangestothedatabaseinsyncwiththegeneratedmodelistousemigrationsi.e.tomakethechangestothemodelfirst,andthenusetoolstogeneratecodethatpropagatesthemodificationstothedatabase.However,dependingonyourcircumstances,thismaynotalwaysbeanoption.Ifyouneedtore-scaffoldthemodelafterdatabaseschemachangeshavebeenmade,youcandosobyspecifyingthe-for--forceoptione.g.: dotnetefdbcontextscaffold"Server=.\;Database=AdventureWorksLT2012;Trusted_Connection=True;"Microsoft.EntityFrameworkCore.SqlServer--force Alloftheclassfileswillbeoverwritten,whichmeansthatanyamendmentsthatyoumighthavemadetotheme.g.addingattributesoradditionalmembers,willbelost.YoucanmitigatethisbyoptingtousetheFluentAPIforconfigurationandusingseparateconfigurationclasses.Inaddition,youcanusepartialclassestodeclareadditionalpropertiesthatdon'tmaptocolumnsinthedatabasetables. VisualStudio IfyouareworkingwithVisualStudio,youcanusethePackageManagerConsolecommandstogeneratethethecodefilesforthemodel.TheequivalentcommandtothelastCLIcommandjustaboveis: PM>Scaffold-DbContext"Server=.\;Database=AdventureWorksLT2012;Trusted_Connection=True;"Microsoft.EntityFrameworkCore.SqlServer-OutputDirModel-Context"AdventureContext"-DataAnnotations Migrations InpreviousversionsofEntityFramework,itwaspossible,oncethemodelhasbeencreated,toaddamigrationthatdidnotaffecttheschemaoftheexistingdatabaseusingthe-ignorechangesoption.ThisoptiondoesnotexistinEntityFrameworkCore,sotheworkaroundistocreateafirstmigrationandthentodeleteorcommentoutthecontentsoftheUpmethodpriortoapplyingthemigrationtothedatabase.Thiswillresultinamodelandadatabaseschemathatmatch. Onthispage Startingwithanexistingdatabase CommandLineInterface ModelConfiguration UpdatingtheModel VisualStudio Migrations LatestUpdates PackageManagerConsoleCommands CommandLineInterfacecommands CommandsinEntityFrameworkCore TheFluentAPIWithOneMethod TheFluentAPIWithManyMethod TheFluentAPIValueGeneratedOnAddOrUpdateMethod
延伸文章資訊
- 1Generating a model from an existing database
You use the DbContext Scaffold command to generate the model. The command has two required argume...
- 2使用Entity Framework Core加入既有資料庫的模型
接著在PMC (Package Manager Console) 下Scaffold-DbContext指令,將建立既有資料庫的EF Core 模型。從選單選取「Tools」 - 「NuGet ...
- 3ASP.NET Core - (DB-First) Scaffold-DbContext的錯誤訊息
初學者常見的錯誤訊息如下(1) 無法辨識'Scaffold-DbContext' 詞彙是否為Cmdlet、函數、指令檔或可執行程式的名稱(2.
- 47.2.2 Scaffolding an Existing Database in EF Core
dotnet ef dbcontext scaffold "connection-string" MySql.EntityFrameworkCore -o sakila -f. To valid...
- 5EF Core Database-First Tutorial for .NET Core - Devart