Generating a model from an existing database

文章推薦指數: 80 %
投票人數:10人

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



請為這篇文章評分?