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
延伸文章資訊
- 1ASP.NET Core - (DB-First) Scaffold-DbContext的錯誤訊息
初學者常見的錯誤訊息如下(1) 無法辨識'Scaffold-DbContext' 詞彙是否為Cmdlet、函數、指令檔或可執行程式的名稱(2.
- 2DbContext lifetime in desktop app with SQLite - Microsoft Q&A
- 3NET Core第10天_搭配EF Core串聯資料庫Db First - iT 邦幫忙
#warning To protect potentially sensitive information in your connection string, you should move ...
- 4使用EF Core在既有資料庫(Model First or DB First)的注意事項
Scaffold-DbContext "Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;" Mic...
- 5EF Core 工具參考(套件管理員主控台) - Microsoft Learn
... Scaffold-DbContext; Script-DbContext; Script-Migration; Update-Database; 其他資源. 適用于Entity Fram...