dotnet ef dbcontext scaffold. Generates code for a DbContext and entity types for a database. In order for this command to generate an entity ...
Skiptomaincontent
Thisbrowserisnolongersupported.
UpgradetoMicrosoftEdgetotakeadvantageofthelatestfeatures,securityupdates,andtechnicalsupport.
DownloadMicrosoftEdge
MoreinfoaboutInternetExplorerandMicrosoftEdge
Tableofcontents
Exitfocusmode
ReadinEnglish
Save
Tableofcontents
ReadinEnglish
Save
Feedback
Edit
Print
Twitter
LinkedIn
Facebook
Email
Tableofcontents
EntityFrameworkCoretoolsreference-.NETCoreCLI
Article
05/11/2022
11minutestoread
9contributors
Inthisarticle
Thecommand-lineinterface(CLI)toolsforEntityFrameworkCoreperformdesign-timedevelopmenttasks.Forexample,theycreatemigrations,applymigrations,andgeneratecodeforamodelbasedonanexistingdatabase.Thecommandsareanextensiontothecross-platformdotnetcommand,whichispartofthe.NETCoreSDK.Thesetoolsworkwith.NETCoreprojects.
WhenusingVisualStudio,considerusingthePackageManagerConsoletoolsinsteadoftheCLItools.PackageManagerConsoletoolsautomatically:
WorkswiththecurrentprojectselectedinthePackageManagerConsolewithoutrequiringthatyoumanuallyswitchdirectories.
Opensfilesgeneratedbyacommandafterthecommandiscompleted.
Providestabcompletionofcommands,parameters,projectnames,contexttypes,andmigrationnames.
Installingthetools
dotnetefcanbeinstalledaseitheraglobalorlocaltool.Mostdeveloperspreferinstallingdotnetefasaglobaltoolusingthefollowingcommand:
dotnettoolinstall--globaldotnet-ef
Touseitasalocaltool,restorethedependenciesofaprojectthatdeclaresitasatoolingdependencyusingatoolmanifestfile.
Updatethetoolusingthefollowingcommand:
dotnettoolupdate--globaldotnet-ef
Beforeyoucanusethetoolsonaspecificproject,you'llneedtoaddtheMicrosoft.EntityFrameworkCore.Designpackagetoit.
dotnetaddpackageMicrosoft.EntityFrameworkCore.Design
Verifyinstallation
RunthefollowingcommandstoverifythatEFCoreCLItoolsarecorrectlyinstalled:
dotnetef
Theoutputfromthecommandidentifiestheversionofthetoolsinuse:
_/\__
---==/\\
______|.\|\
|__||__||)\\\
|_||_|\_/|//|\\
|___||_|/\\\/\\
EntityFrameworkCore.NETCommand-lineTools2.1.3-rtm-32065
Updatethetools
Usedotnettoolupdate--globaldotnet-eftoupdatetheglobaltoolstothelatestavailableversion.Ifyouhavethetoolsinstalledlocallyinyourprojectusedotnettoolupdatedotnet-ef.Installaspecificversionbyappending--versiontoyourcommand.SeetheUpdatesectionofthedotnettooldocumentationformoredetails.
Usingthetools
Beforeusingthetools,youmighthavetocreateastartupprojectorsettheenvironment.
Targetprojectandstartupproject
Thecommandsrefertoaprojectandastartupproject.
Theprojectisalsoknownasthetargetprojectbecauseit'swherethecommandsaddorremovefiles.Bydefault,theprojectinthecurrentdirectoryisthetargetproject.Youcanspecifyadifferentprojectastargetprojectbyusingthe--projectoption.
Thestartupprojectistheonethatthetoolsbuildandrun.Thetoolshavetoexecuteapplicationcodeatdesigntimetogetinformationabouttheproject,suchasthedatabaseconnectionstringandtheconfigurationofthemodel.Bydefault,theprojectinthecurrentdirectoryisthestartupproject.Youcanspecifyadifferentprojectasstartupprojectbyusingthe--startup-projectoption.
Thestartupprojectandtargetprojectareoftenthesameproject.Atypicalscenariowheretheyareseparateprojectsiswhen:
TheEFCorecontextandentityclassesareina.NETCoreclasslibrary.
A.NETCoreconsoleapporwebappreferencestheclasslibrary.
It'salsopossibletoputmigrationscodeinaclasslibraryseparatefromtheEFCorecontext.
Othertargetframeworks
TheCLItoolsworkwith.NETCoreprojectsand.NETFrameworkprojects.AppsthathavetheEFCoremodelina.NETStandardclasslibrarymightnothavea.NETCoreor.NETFrameworkproject.Forexample,thisistrueofXamarinandUniversalWindowsPlatformapps.Insuchcases,youcancreatea.NETCoreconsoleappprojectwhoseonlypurposeistoactasstartupprojectforthetools.Theprojectcanbeadummyprojectwithnorealcode—itisonlyneededtoprovideatargetforthetooling.
Whyisadummyprojectrequired?Asmentionedearlier,thetoolshavetoexecuteapplicationcodeatdesigntime.Todothat,theyneedtousethe.NETCoreruntime.WhentheEFCoremodelisinaprojectthattargets.NETCoreor.NETFramework,theEFCoretoolsborrowtheruntimefromtheproject.Theycan'tdothatiftheEFCoremodelisina.NETStandardclasslibrary.The.NETStandardisnotanactual.NETimplementation;it'saspecificationofasetofAPIsthat.NETimplementationsmustsupport.Therefore.NETStandardisnotsufficientfortheEFCoretoolstoexecuteapplicationcode.Thedummyprojectyoucreatetouseasstartupprojectprovidesaconcretetargetplatformintowhichthetoolscanloadthe.NETStandardclasslibrary.
ASP.NETCoreenvironment
TospecifytheenvironmentforASP.NETCoreprojects,settheASPNETCORE_ENVIRONMENTenvironmentvariablebeforerunningcommands.
StartinginEFCore5.0,additionalargumentscanalsobepassedintoProgram.CreateHostBuilderallowingyoutospecifytheenvironmentonthecommand-line:
dotnetefdatabaseupdate----environmentProduction
Tip
The--tokendirectsdotneteftotreateverythingthatfollowsasanargumentandnottrytoparsethemasoptions.Anyextraargumentsnotusedbydotnetefareforwardedtotheapp.
Commonoptions
Option
Short
Description
--json
ShowJSONoutput.
--context
-c
TheDbContextclasstouse.Classnameonlyorfullyqualifiedwithnamespaces.Ifthisoptionisomitted,EFCorewillfindthecontextclass.Iftherearemultiplecontextclasses,thisoptionisrequired.
--project
-p
Relativepathtotheprojectfolderofthetargetproject.Defaultvalueisthecurrentfolder.
--startup-project
-s
Relativepathtotheprojectfolderofthestartupproject.Defaultvalueisthecurrentfolder.
--framework
TheTargetFrameworkMonikerforthetargetframework.Usewhentheprojectfilespecifiesmultipletargetframeworks,andyouwanttoselectoneofthem.
--configuration
Thebuildconfiguration,forexample:DebugorRelease.
--runtime
Theidentifierofthetargetruntimetorestorepackagesfor.ForalistofRuntimeIdentifiers(RIDs),seetheRIDcatalog.
--no-build
Don'tbuildtheproject.Intendedtobeusedwhenthebuildisup-to-date.
--help
-h
Showhelpinformation.
--verbose
-v
Showverboseoutput.
--no-color
Don'tcolorizeoutput.
--prefix-output
Prefixoutputwithlevel.
StartinginEFCore5.0,anyadditionalargumentsarepassedtotheapplication.
dotnetefdatabasedrop
Deletesthedatabase.
Options:
Option
Short
Description
--force
-f
Don'tconfirm.
--dry-run
Showwhichdatabasewouldbedropped,butdon'tdropit.
Thecommonoptionsarelistedabove.
dotnetefdatabaseupdate
Updatesthedatabasetothelastmigrationortoaspecifiedmigration.
Arguments:
Argument
Description
Thetargetmigration.MigrationsmaybeidentifiedbynameorbyID.Thenumber0isaspecialcasethatmeansbeforethefirstmigrationandcausesallmigrationstobereverted.Ifnomigrationisspecified,thecommanddefaultstothelastmigration.
Options:
Option
Description
--connection
Theconnectionstringtothedatabase.DefaultstotheonespecifiedinAddDbContextorOnConfiguring.AddedinEFCore5.0.
Thecommonoptionsarelistedabove.
Thefollowingexamplesupdatethedatabasetoaspecifiedmigration.ThefirstusesthemigrationnameandthesecondusesthemigrationIDandaspecifiedconnection:
dotnetefdatabaseupdateInitialCreate
dotnetefdatabaseupdate20180904195021_InitialCreate--connectionyour_connection_string
dotnetefdbcontextinfo
GetsinformationaboutaDbContexttype.
Thecommonoptionsarelistedabove.
dotnetefdbcontextlist
ListsavailableDbContexttypes.
Thecommonoptionsarelistedabove.
dotnetefdbcontextoptimize
GeneratesacompiledversionofthemodelusedbytheDbContext.AddedinEFCore6.
SeeCompiledmodelsformoreinformation.
Options:
Option
Short
Description
--output-dir
-o
Thedirectorytoputfilesin.Pathsarerelativetotheprojectdirectory.
--namespace
-n
Thenamespacetouseforallgeneratedclasses.DefaultstogeneratedfromtherootnamespaceandtheoutputdirectoryplusCompiledModels.
Thecommonoptionsarelistedabove.
ThefollowingexampleusesthedefaultsettingsandworksifthereisonlyoneDbContextintheproject:
dotnetefdbcontextoptimize
Thefollowingexampleoptimizesthemodelforthecontextwiththespecifiednameandplacesitinaseparatefolderandnamespace:
dotnetefdbcontextoptimize-oModels-nBlogModels-cBlogContext
dotnetefdbcontextscaffold
GeneratescodeforaDbContextandentitytypesforadatabase.Inorderforthiscommandtogenerateanentitytype,thedatabasetablemusthaveaprimarykey.
Arguments:
Argument
Description
Theconnectionstringtothedatabase.ForASP.NETCore2.xprojects,thevaluecanbename=.Inthatcasethenamecomesfromtheconfigurationsourcesthataresetupfortheproject.
Theprovidertouse.TypicallythisisthenameoftheNuGetpackage,forexample:Microsoft.EntityFrameworkCore.SqlServer.
Options:
Option
Short
Description
--data-annotations
-d
Useattributestoconfigurethemodel(wherepossible).Ifthisoptionisomitted,onlythefluentAPIisused.
--context
-c
ThenameoftheDbContextclasstogenerate.
--context-dir
ThedirectorytoputtheDbContextclassfilein.Pathsarerelativetotheprojectdirectory.Namespacesarederivedfromthefoldernames.
--context-namespace
ThenamespacetouseforthegeneratedDbContextclass.Note:overrides--namespace.AddedinEFCore5.0.
--force
-f
Overwriteexistingfiles.
--output-dir
-o
Thedirectorytoputentityclassfilesin.Pathsarerelativetotheprojectdirectory.
--namespace
-n
Thenamespacetouseforallgeneratedclasses.Defaultstogeneratedfromtherootnamespaceandtheoutputdirectory.AddedinEFCore5.0.
--schema...
Theschemasoftablestogenerateentitytypesfor.Tospecifymultipleschemas,repeat--schemaforeachone.Ifthisoptionisomitted,allschemasareincluded.
--table...
-t
Thetablestogenerateentitytypesfor.Tospecifymultipletables,repeat-tor--tableforeachone.Ifthisoptionisomitted,alltablesareincluded.
--use-database-names
Usetableandcolumnnamesexactlyastheyappearinthedatabase.Ifthisoptionisomitted,databasenamesarechangedtomorecloselyconformtoC#namestyleconventions.
--no-onconfiguring
SuppressesgenerationoftheOnConfiguringmethodinthegeneratedDbContextclass.AddedinEFCore5.0.
--no-pluralize
Don'tusethepluralizer.AddedinEFCore5.0
Thecommonoptionsarelistedabove.
ThefollowingexamplescaffoldsallschemasandtablesandputsthenewfilesintheModelsfolder.
dotnetefdbcontextscaffold"Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;"Microsoft.EntityFrameworkCore.SqlServer-oModels
Thefollowingexamplescaffoldsonlyselectedtablesandcreatesthecontextinaseparatefolderwithaspecifiednameandnamespace:
dotnetefdbcontextscaffold"Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;"Microsoft.EntityFrameworkCore.SqlServer-oModels-tBlog-tPost--context-dirContext-cBlogContext--context-namespaceNew.Namespace
Thefollowingexamplereadstheconnectionstringfromtheproject'sconfigurationsetusingtheSecretManagertool.
dotnetuser-secretssetConnectionStrings:Blogging"DataSource=(localdb)\MSSQLLocalDB;InitialCatalog=Blogging"
dotnetefdbcontextscaffoldName=ConnectionStrings:BloggingMicrosoft.EntityFrameworkCore.SqlServer
ThefollowingexampleskipsscaffoldinganOnConfiguringmethod.ThiscanbeusefulwhenyouwanttoconfiguretheDbContextoutsideoftheclass.Forexample,ASP.NETCoreappstypicallyconfigureitinStartup.ConfigureServices.AddedinEFCore5.0.
dotnetefdbcontextscaffold"Server=(localdb)\mssqllocaldb;Database=Blogging;UserId=myUsername;Password=myPassword;"Microsoft.EntityFrameworkCore.SqlServer--no-onconfiguring
dotnetefdbcontextscript
GeneratesaSQLscriptfromtheDbContext.Bypassesanymigrations.
Options:
Option
Short
Description
--output
-o
Thefiletowritetheresultto.
Thecommonoptionsarelistedabove.
dotnetefmigrationsadd
Addsanewmigration.
Arguments:
Argument
Description
Thenameofthemigration.
Options:
Option
Short
Description
--output-dir
-o
Thedirectoryusetooutputthefiles.Pathsarerelativetothetargetprojectdirectory.Defaultsto"Migrations".
--namespace
-n
Thenamespacetouseforthegeneratedclasses.Defaultstogeneratedfromtheoutputdirectory.AddedinEFCore5.0.
Thecommonoptionsarelistedabove.
dotnetefmigrationsbundle
Createsanexecutabletoupdatethedatabase.
Options:
Option
Short
Description
--output
-o
Thepathofexecutablefiletocreate.
--force
-f
Overwriteexistingfiles.
--self-contained
Alsobundlethe.NETruntimesoitdoesn'tneedtobeinstalledonthemachine.
--target-runtime
-r
Thetargetruntimetobundlefor.
Thecommonoptionsarelistedabove.
dotnetefmigrationslist
Listsavailablemigrations.
Options:
Option
Description
--connection
Theconnectionstringtothedatabase.DefaultstotheonespecifiedinAddDbContextorOnConfiguring.AddedinEFCore5.0.
--no-connect
Don'tconnecttothedatabase.AddedinEFCore5.0.
Thecommonoptionsarelistedabove.
dotnetefmigrationsremove
Removesthelastmigration,rollingbackthecodechangesthatweredoneforthelatestmigration.
Options:
Option
Short
Description
--force
-f
Revertthelatestmigration,rollingbackbothcodeanddatabasechangesthatweredoneforthelatestmigration.Continuestorollbackonlythecodechangesifanerroroccurswhileconnectingtothedatabase.
Thecommonoptionsarelistedabove.
dotnetefmigrationsscript
GeneratesaSQLscriptfrommigrations.
Arguments:
Argument
Description
Thestartingmigration.MigrationsmaybeidentifiedbynameorbyID.Thenumber0isaspecialcasethatmeansbeforethefirstmigration.Defaultsto0.
Theendingmigration.Defaultstothelastmigration.
Options:
Option
Short
Description
--output
-o
Thefiletowritethescriptto.
--idempotent
-i
Generateascriptthatcanbeusedonadatabaseatanymigration.
--no-transactions
Don'tgenerateSQLtransactionstatements.AddedinEFCore5.0.
Thecommonoptionsarelistedabove.
ThefollowingexamplecreatesascriptfortheInitialCreatemigration:
dotnetefmigrationsscript0InitialCreate
ThefollowingexamplecreatesascriptforallmigrationsaftertheInitialCreatemigration.
dotnetefmigrationsscript20180904195021_InitialCreate
Additionalresources
Migrations
ReverseEngineering
Compiledmodels
Feedback
Submitandviewfeedbackfor
Thisproduct
Thispage
Viewallpagefeedback
Inthisarticle