Reference guide for the Entity Framework Core Visual Studio Package Manager ... Script-Migration; Update-Database; Additional resources.
Skiptomaincontent
Thisbrowserisnolongersupported.
UpgradetoMicrosoftEdgetotakeadvantageofthelatestfeatures,securityupdates,andtechnicalsupport.
DownloadMicrosoftEdge
MoreinfoaboutInternetExplorerandMicrosoftEdge
Tableofcontents
Exitfocusmode
ReadinEnglish
Save
Tableofcontents
ReadinEnglish
Save
Feedback
Edit
Print
Twitter
LinkedIn
Facebook
Email
Tableofcontents
EntityFrameworkCoretoolsreference-PackageManagerConsoleinVisualStudio
Article
12/18/2021
9minutestoread
4contributors
Inthisarticle
ThePackageManagerConsole(PMC)toolsforEntityFrameworkCoreperformdesign-timedevelopmenttasks.Forexample,theycreatemigrations,applymigrations,andgeneratecodeforamodelbasedonanexistingdatabase.ThecommandsruninsideofVisualStudiousingthePackageManagerConsole.Thesetoolsworkwithboth.NETFrameworkand.NETCoreprojects.
Ifyouaren'tusingVisualStudio,werecommendtheEFCoreCommand-lineToolsinstead.The.NETCoreCLItoolsarecross-platformandruninsideacommandprompt.
Installingthetools
InstallthePackageManagerConsoletoolsbyrunningthefollowingcommandinPackageManagerConsole:
Install-PackageMicrosoft.EntityFrameworkCore.Tools
UpdatethetoolsbyrunningthefollowingcommandinPackageManagerConsole.
Update-PackageMicrosoft.EntityFrameworkCore.Tools
Verifytheinstallation
Verifythatthetoolsareinstalledbyrunningthiscommand:
Get-Helpabout_EntityFrameworkCore
Theoutputlookslikethis(itdoesn'ttellyouwhichversionofthetoolsyou'reusing):
_/\__
---==/\\
______|.\|\
|__||__||)\\\
|_||_|\_/|//|\\
|___||_|/\\\/\\
TOPIC
about_EntityFrameworkCore
SHORTDESCRIPTION
ProvidesinformationabouttheEntityFrameworkCorePackageManagerConsoleTools.
Usingthetools
Beforeusingthetools:
Understandthedifferencebetweentargetandstartupproject.
Learnhowtousethetoolswith.NETStandardclasslibraries.
ForASP.NETCoreprojects,settheenvironment.
Targetandstartupproject
Thecommandsrefertoaprojectandastartupproject.
Theprojectisalsoknownasthetargetprojectbecauseit'swherethecommandsaddorremovefiles.Bydefault,theDefaultprojectselectedinPackageManagerConsoleisthetargetproject.Youcanspecifyadifferentprojectastargetprojectbyusingthe-Projectparameter.
Thestartupprojectistheonethatthetoolsbuildandrun.Thetoolshavetoexecuteapplicationcodeatdesigntimetogetinformationabouttheproject,suchasthedatabaseconnectionstringandtheconfigurationofthemodel.Bydefault,theStartupProjectinSolutionExploreristhestartupproject.Youcanspecifyadifferentprojectasstartupprojectbyusingthe-StartupProjectparameter.
Thestartupprojectandtargetprojectareoftenthesameproject.Atypicalscenariowheretheyareseparateprojectsiswhen:
TheEFCorecontextandentityclassesareina.NETCoreclasslibrary.
A.NETCoreconsoleapporwebappreferencestheclasslibrary.
It'salsopossibletoputmigrationscodeinaclasslibraryseparatefromtheEFCorecontext.
Othertargetframeworks
ThePackageManagerConsoletoolsworkwith.NETCoreor.NETFrameworkprojects.AppsthathavetheEFCoremodelina.NETStandardclasslibrarymightnothavea.NETCoreor.NETFrameworkproject.Forexample,thisistrueofXamarinandUniversalWindowsPlatformapps.Insuchcases,youcancreatea.NETCoreor.NETFrameworkconsoleappprojectwhoseonlypurposeistoactasstartupprojectforthetools.Theprojectcanbeadummyprojectwithnorealcode—itisonlyneededtoprovideatargetforthetooling.
Whyisadummyprojectrequired?Asmentionedearlier,thetoolshavetoexecuteapplicationcodeatdesigntime.Todothat,theyneedtousethe.NETCoreor.NETFrameworkruntime.WhentheEFCoremodelisinaprojectthattargets.NETCoreor.NETFramework,theEFCoretoolsborrowtheruntimefromtheproject.Theycan'tdothatiftheEFCoremodelisina.NETStandardclasslibrary.The.NETStandardisnotanactual.NETimplementation;it'saspecificationofasetofAPIsthat.NETimplementationsmustsupport.Therefore.NETStandardisnotsufficientfortheEFCoretoolstoexecuteapplicationcode.Thedummyprojectyoucreatetouseasstartupprojectprovidesaconcretetargetplatformintowhichthetoolscanloadthe.NETStandardclasslibrary.
ASP.NETCoreenvironment
TospecifytheenvironmentforASP.NETCoreprojects,setenv:ASPNETCORE_ENVIRONMENTbeforerunningcommands.
StartinginEFCore5.0,additionalargumentscanalsobepassedintoProgram.CreateHostBuilderallowingyoutospecifytheenvironmentonthecommand-line:
Update-Database-Args'--environmentProduction'
Commonparameters
ThefollowingtableshowsparametersthatarecommontoalloftheEFCorecommands:
Parameter
Description
-Context
TheDbContextclasstouse.Classnameonlyorfullyqualifiedwithnamespaces.Ifthisparameterisomitted,EFCorefindsthecontextclass.Iftherearemultiplecontextclasses,thisparameterisrequired.
-Project
Thetargetproject.Ifthisparameterisomitted,theDefaultprojectforPackageManagerConsoleisusedasthetargetproject.
-StartupProject
Thestartupproject.Ifthisparameterisomitted,theStartupprojectinSolutionpropertiesisusedasthetargetproject.
-Args
Argumentspassedtotheapplication.AddedinEFCore5.0.
-Verbose
Showverboseoutput.
Toshowhelpinformationaboutacommand,usePowerShell'sGet-Helpcommand.
Tip
TheContext,Project,andStartupProjectparameterssupporttab-expansion.
Add-Migration
Addsanewmigration.
Parameters:
Parameter
Description
-Name
Thenameofthemigration.Thisisapositionalparameterandisrequired.
-OutputDir
Thedirectoryusetooutputthefiles.Pathsarerelativetothetargetprojectdirectory.Defaultsto"Migrations".
-Namespace
Thenamespacetouseforthegeneratedclasses.Defaultstogeneratedfromtheoutputdirectory.AddedinEFCore5.0.
Thecommonparametersarelistedabove.
Bundle-Migration
Createsanexecutabletoupdatethedatabase.
Parameters:
Parameter
Description
-Output
Thepathofexecutablefiletocreate.
-Force
Overwriteexistingfiles.
-SelfContained
Alsobundlethe.NETruntimesoitdoesn'tneedtobeinstalledonthemachine.
-TargetRuntime
Thetargetruntimetobundlefor.
-Framework
Thetargetframework.Defaultstothefirstoneintheproject.
Thecommonparametersarelistedabove.
Drop-Database
Dropsthedatabase.
Parameters:
Parameter
Description
-WhatIf
Showwhichdatabasewouldbedropped,butdon'tdropit.
Thecommonparametersarelistedabove.
Get-DbContext
ListsandgetsinformationaboutavailableDbContexttypes.
Thecommonparametersarelistedabove.
Get-Migration
Listsavailablemigrations.AddedinEFCore5.0.
Parameters:
Parameter
Description
-Connection
Theconnectionstringtothedatabase.DefaultstotheonespecifiedinAddDbContextorOnConfiguring.
-NoConnect
Don'tconnecttothedatabase.
Thecommonparametersarelistedabove.
Optimize-DbContext
GeneratesacompiledversionofthemodelusedbytheDbContext.AddedinEFCore6.
SeeCompiledmodelsformoreinformation.
Parameters:
Parameter
Description
-OutputDir
Thedirectorytoputfilesin.Pathsarerelativetotheprojectdirectory.
-Namespace
Thenamespacetouseforallgeneratedclasses.DefaultstogeneratedfromtherootnamespaceandtheoutputdirectoryplusCompiledModels.
Thecommonparametersarelistedabove.
ThefollowingexampleusesthedefaultsandworksifthereisonlyoneDbContextintheproject:
Optimize-DbContext
Thefollowingexampleoptimizesthemodelforthecontextwiththespecifiednameandplacesitinaseparatefolderandnamespace:
Optimize-DbContext-OutputDirModels-NamespaceBlogModels-ContextBlogContext
Remove-Migration
Removesthelastmigration(rollsbackthecodechangesthatweredoneforthemigration).
Parameters:
Parameter
Description
-Force
Revertthemigration(rollbackthechangesthatwereappliedtothedatabase).
Thecommonparametersarelistedabove.
Scaffold-DbContext
GeneratescodeforaDbContextandentitytypesforadatabase.InorderforScaffold-DbContexttogenerateanentitytype,thedatabasetablemusthaveaprimarykey.
Parameters:
Parameter
Description
-Connection
Theconnectionstringtothedatabase.ForASP.NETCore2.xprojects,thevaluecanbename=.Inthatcasethenamecomesfromtheconfigurationsourcesthataresetupfortheproject.Thisisapositionalparameterandisrequired.
-Provider
Theprovidertouse.TypicallythisisthenameoftheNuGetpackage,forexample:Microsoft.EntityFrameworkCore.SqlServer.Thisisapositionalparameterandisrequired.
-OutputDir
Thedirectorytoputentityclassfilesin.Pathsarerelativetotheprojectdirectory.
-ContextDir
ThedirectorytoputtheDbContextfilein.Pathsarerelativetotheprojectdirectory.
-Namespace
Thenamespacetouseforallgeneratedclasses.Defaultstogeneratedfromtherootnamespaceandtheoutputdirectory.AddedinEFCore5.0.
-ContextNamespace
ThenamespacetouseforthegeneratedDbContextclass.Note:overrides-Namespace.AddedinEFCore5.0.
-Context
ThenameoftheDbContextclasstogenerate.
-Schemas
Theschemasoftablestogenerateentitytypesfor.Ifthisparameterisomitted,allschemasareincluded.
-Tables
Thetablestogenerateentitytypesfor.Ifthisparameterisomitted,alltablesareincluded.
-DataAnnotations
Useattributestoconfigurethemodel(wherepossible).Ifthisparameterisomitted,onlythefluentAPIisused.
-UseDatabaseNames
Usetableandcolumnnamesexactlyastheyappearinthedatabase.Ifthisparameterisomitted,databasenamesarechangedtomorecloselyconformtoC#namestyleconventions.
-Force
Overwriteexistingfiles.
-NoOnConfiguring
Don'tgenerateDbContext.OnConfiguring.AddedinEFCore5.0.
-NoPluralize
Don'tusethepluralizer.AddedinEFCore5.0.
Thecommonparametersarelistedabove.
Example:
Scaffold-DbContext"Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;"Microsoft.EntityFrameworkCore.SqlServer-OutputDirModels
Examplethatscaffoldsonlyselectedtablesandcreatesthecontextinaseparatefolderwithaspecifiednameandnamespace:
Scaffold-DbContext"Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;"Microsoft.EntityFrameworkCore.SqlServer-OutputDirModels-Tables"Blog","Post"-ContextDirContext-ContextBlogContext-ContextNamespaceNew.Namespace
Thefollowingexamplereadstheconnectionstringfromtheproject'sconfigurationpossiblysetusingtheSecretManagertool.
Scaffold-DbContext"Name=ConnectionStrings:Blogging"Microsoft.EntityFrameworkCore.SqlServer
Script-DbContext
GeneratesaSQLscriptfromtheDbContext.Bypassesanymigrations.
Parameters:
Parameter
Description
-Output
Thefiletowritetheresultto.
Thecommonparametersarelistedabove.
Script-Migration
GeneratesaSQLscriptthatappliesallofthechangesfromoneselectedmigrationtoanotherselectedmigration.
Parameters:
Parameter
Description
-From
Thestartingmigration.MigrationsmaybeidentifiedbynameorbyID.Thenumber0isaspecialcasethatmeansbeforethefirstmigration.Defaultsto0.
-To
Theendingmigration.Defaultstothelastmigration.
-Idempotent
Generateascriptthatcanbeusedonadatabaseatanymigration.
-NoTransactions
Don'tgenerateSQLtransactionstatements.AddedinEFCore5.0.
-Output
Thefiletowritetheresultto.IFthisparameterisomitted,thefileiscreatedwithageneratednameinthesamefolderastheapp'sruntimefilesarecreated,forexample:/obj/Debug/netcoreapp2.1/ghbkztfz.sql/.
Thecommonparametersarelistedabove.
Tip
TheTo,From,andOutputparameterssupporttab-expansion.
ThefollowingexamplecreatesascriptfortheInitialCreatemigration(fromadatabasewithoutanymigrations),usingthemigrationname.
Script-Migration0InitialCreate
ThefollowingexamplecreatesascriptforallmigrationsaftertheInitialCreatemigration,usingthemigrationID.
Script-Migration20180904195021_InitialCreate
Update-Database
Updatesthedatabasetothelastmigrationortoaspecifiedmigration.
Parameter
Description
-Migration
Thetargetmigration.MigrationsmaybeidentifiedbynameorbyID.Thenumber0isaspecialcasethatmeansbeforethefirstmigrationandcausesallmigrationstobereverted.Ifnomigrationisspecified,thecommanddefaultstothelastmigration.
-Connection
Theconnectionstringtothedatabase.DefaultstotheonespecifiedinAddDbContextorOnConfiguring.AddedinEFCore5.0.
Thecommonparametersarelistedabove.
Tip
TheMigrationparametersupportstab-expansion.
Thefollowingexamplerevertsallmigrations.
Update-Database0
Thefollowingexamplesupdatethedatabasetoaspecifiedmigration.ThefirstusesthemigrationnameandthesecondusesthemigrationIDandaspecifiedconnection:
Update-DatabaseInitialCreate
Update-Database20180904195021_InitialCreate-Connectionyour_connection_string
Additionalresources
Migrations
ReverseEngineering
Compiledmodels
Feedback
Submitandviewfeedbackfor
Thisproduct
Thispage
Viewallpagefeedback
Inthisarticle