7.2.2 Scaffolding an Existing Database in EF Core
文章推薦指數: 80 %
dotnet ef dbcontext scaffold "connection-string" MySql.EntityFrameworkCore -o sakila -f. To validate that the model has been created, open the new sakila ... SkiptoMainContent DocumentationHome MySQLConnector/NETDeveloperGuide PrefaceandLegalNotices IntroductiontoMySQLConnector/NET Connector/NETVersions Connector/NETInstallation InstallingConnector/NETonWindows InstallingConnector/NETUsingMySQLInstaller InstallingConnector/NETUsingtheStandaloneInstaller InstallingConnector/NETUsingNuGet InstallingConnector/NETonUnixwithMono InstallingConnector/NETfromSource Connector/NETConnections CreatingaConnector/NETConnectionString ManagingaConnectionPoolinConnector/NET HandlingConnectionErrors Connector/NETAuthentication Connector/NET8.0ConnectionOptionsReference Connector/NETProgramming UsingGetSchemaonaConnection UsingMySqlCommand UsingConnector/NETwithTableCaching PreparingStatementsinConnector/NET CreatingandCallingStoredProcedures HandlingBLOBDataWithConnector/NET PreparingtheMySQLServer WritingaFiletotheDatabase ReadingaBLOBfromtheDatabasetoaFileonDisk WorkingwithPartialTrust/MediumTrust EvolutionofPartialTrustSupportAcrossConnector/NETVersions ConfiguringPartialTrustwithConnector/NETLibraryInstalledinGAC ConfiguringPartialTrustwithConnector/NETLibraryNotInstalledinGAC WritingaCustomAuthenticationPlugin UsingtheConnector/NETInterceptorClasses HandlingDateandTimeInformationinConnector/NET FractionalSeconds ProblemswhenUsingInvalidDates RestrictingInvalidDates HandlingInvalidDates HandlingNULLDates UsingtheMySqlBulkLoaderClass UsingtheConnector/NETTraceSourceObject ViewingMySQLTraceInformation BuildingCustomListeners UsingConnector/NETwithCrystalReports CreatingaDataSource CreatingtheReport DisplayingtheReport AsynchronousMethods BinaryandNonbinaryIssues CharacterSetConsiderationsforConnector/NET Connector/NETTutorials Tutorial:AnIntroductiontoConnector/NETProgramming TheMySqlConnectionObject TheMySqlCommandObject WorkingwithDecoupledData WorkingwithParameters WorkingwithStoredProcedures ASP.NETProviderModelandTutorials Tutorial:Connector/NETASP.NETMembershipandRoleProvider Tutorial:Connector/NETASP.NETProfileProvider Tutorial:WebPartsPersonalizationProvider Tutorial:SimpleMembershipWebProvider Tutorial:UsinganEntityFrameworkEntityasaWindowsFormsData Source Tutorial:DataBindinginASP.NETUsingLINQonEntities Tutorial:GeneratingMySQLDDLfromanEntityFrameworkModel Tutorial:BasicCRUDOperationswithConnector/NET Tutorial:ConfiguringSSLwithConnector/NET UsingPEMCertificatesinConnector/NET UsingPFXCertificatesinConnector/NET Tutorial:UsingMySqlScript Connector/NETforEntityFramework EntityFramework6Support EntityFrameworkCoreSupport CreatingaDatabasewithCodeFirstinEFCore ScaffoldinganExistingDatabaseinEFCore ConfiguringCharacterSetsandCollationsinEFCore Connector/NETAPIReference MySql.Data.MySqlClientNamespace MySql.Data.MySqlClient.AuthenticationNamespace MySql.Data.MySqlClient.InterceptorsNamespace MySql.Data.MySqlClient.ReplicationNamespace MySql.Data.TypesNamespace Microsoft.EntityFrameworkCoreNamespace MySql.EntityFrameworkCoreNamespace MySql.Data.EntityFrameworkNamespace MySql.WebNamespace Connector/NETSupport Connector/NETCommunitySupport HowtoReportConnector/NETProblemsorBugs Connector/NETFAQ RelatedDocumentation MySQLConnector/NETReleaseNotes Download thisManual PDF(USLtr) -1.3Mb PDF(A4) -1.3Mb MySQLConnector/NETDeveloperGuide / ... / Connector/NETforEntityFramework / EntityFrameworkCoreSupport / ScaffoldinganExistingDatabaseinEFCore 7.2.2 ScaffoldinganExistingDatabaseinEFCore ScaffoldingadatabaseproducesanEntityFrameworkmodelfroman existingdatabase.Theresultingentitiesarecreatedandmappedto thetablesinthespecifieddatabase.Foranoverviewofthe requirementstouseEFCorewithMySQL,see Table 7.2,“Connector/NETVersionsandEntityFrameworkCoreSupport”). NuGetpackageshavetheabilitytoselectthebesttargetfora project,whichmeansthatNuGetinstallsthelibrariesrelatedto thatspecificframeworkversion. Therearetwodifferentwaystoscaffoldanexistingdatabase: Scaffolding aDatabaseUsing.NETCoreCLI Scaffolding aDatabaseUsingPackageManagerConsoleinVisualStudio Thissectionshowshowtoscaffoldthesakila databaseusingbothapproaches.Additionalscaffoldingtechniques are: Scaffolding aDatabasebyFilteringTables Scaffolding withMultipleSchemas Requirements Forthecomponentsneededtoreproduceeachscaffoldingapproach, see GeneralRequirementsforEFCoreSupport. WiththePackageManagerConsoleapproach,determinewhichversion ofVisualStudioisrecommendedfortheversionof.NETor.NET Coreinuse(see Table 2.1,“Connector/NETRequirementsforRelatedProducts”). Todownloadsakiladatabase,see https://dev.mysql.com/doc/sakila/en/. Note WhenupgradingASP.NETCoreapplicationstoanewerframework, besuretousetheappropriateEFCoreversion(see https://docs.microsoft.com/en-us/aspnet/core/migration/30-to-31?view=aspnetcore-3.1). ScaffoldingaDatabaseUsing.NETCoreCLI Initializeavalid.NETCoreprojectandconsoleapplication usingthe.NETCorecommand-lineinterface(CLI)andthen changetothenewlycreatedfolder (sakilaConsole). dotnetnewconsole–osakilaConsolecdsakilaConsole AddtheMySQLNuGetpackageforEFCoreusingtheCLI.For example,usethefollowingcommandtoaddtheMySQLEFCore 6.0packageforusewithConnector/NET8.0.31andlater. dotnetaddpackageMySql.EntityFrameworkCore--version6.0.4 UseoneofthefollowingcommandstoaddeithertheMySQLEF Core5.0orEFCore3.1packageforusewithConnector/NET8.0.23and later. dotnetaddpackageMySql.EntityFrameworkCore--version5.0.16 dotnetaddpackageMySql.EntityFrameworkCore--version3.1.24 ForpreviousversionsofConnector/NET,usethefollowingcommandto specifytheversionofthepackage: dotnetaddpackageMySql.Data.EntityFrameworkCore--version8.0.22 Addthefollowing Microsoft.EntityFrameworkCore.DesignNuget package: dotnetaddpackageMicrosoft.EntityFrameworkCore.Tools Restoredependenciesandproject-specifictoolsthatare specifiedintheprojectfileasfollows: dotnetrestore CreatetheEntityFrameworkCoremodelbyexecutingthe followingcommand.Theconnectionstringforthisexamplemust includedatabase=sakila.Forinformation aboutusingconnectionstrings,see Section 4.1,“CreatingaConnector/NETConnectionString”. Note IfyouareusingaconnectorversionearlierthanConnector/NET 8.0.23,replaceMySql.EntityFrameworkCore withMySql.Data.EntityFrameworkCore. dotnetefdbcontextscaffold"connection-string"MySql.EntityFrameworkCore-osakila-f Tovalidatethatthemodelhasbeencreated,openthenew sakilafolder.Youshouldseefiles correspondingtoalltablesmappedtoentities.Inaddition, lookforthesakilaContext.csfile,which containstheDbContextforthisdatabase. ScaffoldingaDatabaseUsingPackageManagerConsoleinVisualStudio OpenVisualStudioandcreateanewConsoleApp (.NETCore)forC#. AddtheMySQLNuGetpackageforEFCoreusingthe PackageManagerConsole.For example,usethefollowingcommandtoaddtheMySQLEFCore 6.0packageforusetheConnector/NET8.0.31andlater. Install-PackageMySql.EntityFrameworkCore-Version6.0.4 UseoneofthefollowingcommandstoaddeithertheMySQLEF Core5.0orEFCore3.1packageforusewithConnector/NET8.0.23and later. Install-PackageMySql.EntityFrameworkCore-Version5.0.16 Install-PackageMySql.EntityFrameworkCore-Version3.1.24 ForpreviousversionsofConnector/NET,usethefollowingcommandto specifytheversionofthepackage: Install-PackageMySql.Data.EntityFrameworkCore-Version8.0.22 InstallthefollowingNuGetpackagebyselectingeither PackageManagerConsole(or ManageNuGetPackagesforSolution andthenNuGetPackageManager)from theToolsmenu: Microsoft.EntityFrameworkCore.Tools. OpenPackageManagerConsoleand enterthefollowingcommandattheprompttocreatethe entitiesandDbContextforthe sakiladatabase.Theconnectionstringfor thisexamplemustincludedatabase=sakila. Forinformationaboutusingconnectionstrings,see Section 4.1,“CreatingaConnector/NETConnectionString”. Note IfyouareusingaconnectorversionearlierthanConnector/NET 8.0.23,replaceMySql.EntityFrameworkCore withMySql.Data.EntityFrameworkCore. Scaffold-DbContext"connection-string"MySql.EntityFrameworkCore-OutputDirsakila-f VisualStudiocreatesanewsakilafolder insidetheproject,whichcontainsallthetablesmappedto entitiesandthesakilaContext.csfile. ScaffoldingaDatabasebyFilteringTables Itispossibletospecifytheexacttablesinaschematousewhen scaffoldingdatabaseandtoomittherest.Thecommand-line examplesthatfollowshowtheparametersneededforfiltering tables.Theconnectionstringforthisexamplemustinclude database=sakila. IfyouareusingaconnectorversionearlierthanConnector/NET8.0.23, replaceMySql.EntityFrameworkCorewith MySql.Data.EntityFrameworkCore. .NETCoreCLI: dotnetefdbcontextscaffold"connection-string"MySql.EntityFrameworkCore-osakila-tactor-tfilm-tfilm_actor-tlanguage-f PackageManagerConsoleinVisualStudio: Scaffold-DbContext"connection-string"MySql.EntityFrameworkCore-OutputDirSakila-Tablesactor,film,language-f ScaffoldingwithMultipleSchemas Whenscaffoldingadatabase,youcanusemorethanoneschemaor database.NotethattheaccountusedtoconnecttotheMySQL servermusthaveaccesstoeachschematobeincludedwithinthe context. Thefollowingcommand-lineexamplesshowhowtoincorporatethe sakilaandworldschemas withinasinglecontext.Ifyouareusingaconnectorversion earlierthanConnector/NET8.0.23,replace MySql.EntityFrameworkCorewith MySql.Data.EntityFrameworkCore. .NETCoreCLI: dotnetefdbcontextscaffold"connection-string"MySql.EntityFrameworkCore-osakila--schemasakila--schemaworld-f PackageManagerConsoleinVisualStudio: Scaffold-DbContext"connection-string"MySql.EntityFrameworkCore-OutputDirSakila-Schemassakila,world-f PREV HOME UP NEXT RelatedDocumentation MySQLConnector/NETReleaseNotes Download thisManual PDF(USLtr) -1.3Mb PDF(A4) -1.3Mb
延伸文章資訊
- 17.2.2 Scaffolding an Existing Database in EF Core
dotnet ef dbcontext scaffold "connection-string" MySql.EntityFrameworkCore -o sakila -f. To valid...
- 2Generating a model from an existing database
You use the DbContext Scaffold command to generate the model. The command has two required argume...
- 3Scaffolding in Razor Pages
- 4使用EF Core在既有資料庫(Model First or DB First)的注意事項
Scaffold-DbContext "Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;" Mic...
- 5EF Core Database-First Tutorial for .NET Core - Devart