update the database from package manager console in code ...

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

I'm trying to update the database from package Manager console.If my Domain class change, I have to drop and create the database,Instead of dropping the ... Home Public Questions Tags Users Companies Collectives ExploreCollectives Teams StackOverflowforTeams –Startcollaboratingandsharingorganizationalknowledge. CreateafreeTeam WhyTeams? Teams CreatefreeTeam Collectives™onStackOverflow Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost. LearnmoreaboutCollectives Teams Q&Aforwork Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch. LearnmoreaboutTeams updatethedatabasefrompackagemanagerconsoleincodefirstenvironment AskQuestion Asked 7years,1monthago Modified 4years,3monthsago Viewed 103ktimes 31 CodeFirstEnvironment I'mtryingtoupdatethedatabasefrompackageManagerconsole.IfmyDomainclasschange,Ihavetodropandcreatethedatabase,InsteadofdroppingtheDatabasehowcaniupdatethedatabase. Ihavealreadytrybyreadingsomeblogsingoogle. commands PM>Install-PackageEntityFramework ByusingthiscommandiinstalltheEntityFrameworksuccessfully. PM>Enable-Migrations ByusingthiscommanditcreatedtheMigrationfileinmyproject. PM>Update-Database Byusingthiscommand,imayupdatethetablebutihaveaProblemhere. Error Specifythe'-Verbose'flagtoviewtheSQLstatementsbeingappliedtothetargetdatabase. System.Data.SqlClient.SqlException(0x80131904):Anetwork-relatedorinstance-specificerroroccurredwhileestablishingaconnectiontoSQLServer.Theserverwasnotfoundorwasnotaccessible.VerifythattheinstancenameiscorrectandthatSQLServerisconfiguredtoallowremoteconnections. Doubtishere SometimesItmayupdateifonlyonefieldchangesinPOCOClass.ForexampleIhaveUpdatedthemorenumberofDomainclass,HowcaniUpdatetheDatabasefromPackagemanagerConsole.AnyIdea? c#sql-servervisual-studio-2012entity-framework-6entity-framework-migrations Share Improvethisquestion Follow editedJun20,2020at9:12 CommunityBot 111silverbadge askedAug25,2015at4:50 vinodhvinodh 68411goldbadge77silverbadges2020bronzebadges 2 1 Asitstates,youcannotconnect.CheckifSQLServerisrunningandyouhavecorrectconnectionstring. – LukaszSzozda Aug25,2015at4:51 IhaveaddedtheconnectionstringinConfigurationfile – vinodh Aug25,2015at4:53 Addacomment  |  5Answers 5 Sortedby: Resettodefault Highestscore(default) Trending(recentvotescountmore) Datemodified(newestfirst) Datecreated(oldestfirst) 27 YoucanspecifyconnectionstringviaConnectionStringparameter: Update-Database-ConnectionString"datasource=server_name;initialcatalog=db_name;integratedsecurity=True;MultipleActiveResultSets=True;App=EntityFramework"-ConnectionProviderName"System.Data.SqlClient"-Verbose AlsoyouneedtousethisparameterwiththesamevalueforAdd-Migrationcommand: Add-MigrationVersion_Name-ConnectionString"datasource=server_name;initialcatalog=db_name;integratedsecurity=True;MultipleActiveResultSets=True;App=EntityFramework"-ConnectionProviderName"System.Data.SqlClient"-Verbose Share Improvethisanswer Follow editedAug25,2015at5:15 answeredAug25,2015at5:02 atleast3andnomorethan30atleast3andnomorethan30 8611111silverbadges1313bronzebadges 12 IfiusethiscommandimayabletoupdatethedatabaseifchangesinsinglePOCOclass.IfihavechangedmorenumberofDomaincalssField,howcaniupdate? – vinodh Aug25,2015at5:04 Ifiusethiscommandigotfollowingerror.Scaffoldingmigration'update1'.TheDesignerCodeforthismigrationfileincludesasnapshotofyourcurrentCodeFirstmodel.Thissnapshotisusedtocalculatethechangestoyourmodelwhenyouscaffoldthenextmigration.Ifyoumakeadditionalchangestoyourmodelthatyouwanttoincludeinthismigration,thenyoucanre-scaffolditbyrunning'Add-Migrationupdate1'again – vinodh Aug25,2015at5:10 6 Doesn'tworkforme.OUTPUT:Update-Database:Aparametercannotbefoundthatmatchesparametername'ConnectionString'. – Edward Jun10,2017at2:15 1 @Marcus-Tryusing-ConnectionStringNameastheparameter.So,ifyouhaveaconnectionstringinyourconfigfilenamedMyConnectionyourupdate-databasecommandwouldlooklikethis:update-database-ConnectionStringNameMyConnection – MikeDevenney Apr10,2018at0:36 1 ForNetCoreapps(EFCore5),thecommandisUpdate-Database-Connection – Aquiles Apr21at14:12  |  Show7morecomments 7 Iused Enable-Migrations-EnableAutomaticMigrations-Force then Update-Database Andthismigratedmychanges(additionalcolumns)whilepreservingmytestdata.Ithinkthisisthelaziestoptionwhileprototyping. Share Improvethisanswer Follow answeredFeb20,2017at19:37 toddmotoddmo 19.1k1313goldbadges8989silverbadges100100bronzebadges Addacomment  |  2 Lookslikeyouhavemultipleissues.Regardingnotwantingtodropandrecreatethedatabase,thatisdeterminedbyyourdatabaseinitializer.IfyouwanttousemigrationsyouchangeittoMigrateDatabaseToLatestVersion.http://www.codeguru.com/csharp/article.php/c19999/Understanding-Database-Initializers-in-Entity-Framework-Code-First.htm Second,itdoesn'tmatterhowmanyfieldsyouchange,theywillberolledintoasinglemigrationbasedonchangesfromthelastmigration. Third,astheothershavepointedout,itseemsyouhaveaconnectionstringissue.WhileyoucanaddthattoAdd-MigrationandUpdate-MigrationIwouldprobablyfixitintheapplication.Isetmineintheconstructorofmycontextwhichpointstomyconfigfile(web.configforASP.NET). publicclassApplicationDbContext:DbContext { publicApplicationDbContext() :base("MyConnection",throwIfV1Schema:false) { Database.SetInitializer(newMigrateDatabaseToLatestVersion()); } ... Share Improvethisanswer Follow editedFeb1,2017at19:16 answeredAug25,2015at16:27 SteveGreeneSteveGreene 11.7k11goldbadge3131silverbadges5050bronzebadges 2 Ididn'tdownvoteyou,butIgotacompilererrorwhentryingtouseyoursnippet:Thetypeargumentsformethod'System.Data.Entity.Database.SetInitializer(System.Data.Entity.IDatabaseInitializer)'cannotbeinferredfromtheusage.Tryspecifyingthetypeargumentsexplicitly – dcp Feb1,2017at15:38 ThatcanbecorrectedwithDatabase.SetInitializer(...orwhateveryourcontexttypeis.Mineworkswithoutitthough. – SteveGreene Feb1,2017at19:15 Addacomment  |  1 Wheretoputtheconnectionstring? Youdonotneedtospecifyitwitheverycommandinthepackagemanagerconsole.Youcanputitinappsettings.jsonintheprojectwhereyourDbContextclass(read"fromDbContextderivedclass")resides. { "ConnectionStrings":{ "MyConnectionString":"Server=yourServer;Port=5432;Database=yourDatabase;UserId=yourDatabaseUsername;Password=yourDatabasePassword;" } } Itwillbeusedformigrations. Important:Ifyouhavemultipleprojectsinyoursolution,youmustselecttheprojectinthe'Defaultproject'-dropdown(inthePackagemanagerConsole)andyoumustsettheprojectasyourstartupproject(intheSolutionExplorer). Failingtodoso,mightcausethewrongappsettings.jsontobeusedwithanincorrect/differentconnectionstring. ThiswasmyexperiencewithEFCore2.1andprobablyappliestotheotherversionsofEF. Share Improvethisanswer Follow editedJul11,2018at14:34 answeredJul11,2018at14:07 RWCRWC 4,28022goldbadges2020silverbadges2424bronzebadges 1 Settingthestartupprojectworkedforme.Otherwiseitwasreadingtheappsettings.jsonfilefromadifferentproject.Thanksforthetip! – rsbarro May1,2019at15:37 Addacomment  |  0 YouneedtoupdateSSDT gototools>extensionandupdates>updates>SQLserverdatatools Share Improvethisanswer Follow answeredAug18,2017at14:31 ayamouradayamourad 1 1 Downvoted,eventhoughitwon'tshow.NosuchoptionexistsinVisualStudio2017! – user3393933 Dec6,2017at9:49 Addacomment  |  YourAnswer ThanksforcontributingananswertoStackOverflow!Pleasebesuretoanswerthequestion.Providedetailsandshareyourresearch!Butavoid…Askingforhelp,clarification,orrespondingtootheranswers.Makingstatementsbasedonopinion;backthemupwithreferencesorpersonalexperience.Tolearnmore,seeourtipsonwritinggreatanswers. Draftsaved Draftdiscarded Signuporlogin SignupusingGoogle SignupusingFacebook SignupusingEmailandPassword Submit Postasaguest Name Email Required,butnevershown PostYourAnswer Discard Byclicking“PostYourAnswer”,youagreetoourtermsofservice,privacypolicyandcookiepolicy Nottheansweryou'relookingfor?Browseotherquestionstaggedc#sql-servervisual-studio-2012entity-framework-6entity-framework-migrationsoraskyourownquestion. TheOverflowBlog HowtoearnamillionreputationonStackOverflow:beofservicetoothers Therightwaytojobhop(Ep.495) FeaturedonMeta BookmarkshaveevolvedintoSaves Inboximprovements:markingnotificationsasread/unread,andafiltered... Revieweroverboard!Orarequesttoimprovetheonboardingguidancefornew... CollectivesUpdate:RecognizedMembers,Articles,andGitLab Shouldweburninatethe[script]tag? Visitchat Linked 0 Anetwork-relatedorinstance-specificerroroccurredwhileestablishingaconnectiontoSQLServer.OnlocalhostwithEntityFramework Related 1550 HowdoIupdatetheGUIfromanotherthread? 2 HowtoviewtheEFCodeFirstMigrationschangesbeforecalling'Update-Database' 47 WherecanIfindtheconsoleordebugoutputfromcodeexecutedinthepackagemanagerwindow? 3 MVC4-cannotcreatedatabaseusingNuGetPackagemanagerconsole 75 EntityFrameworkcode-first:migrationfailswithupdate-database,forcesunneccessary(?)add-migration 23 Errorinupdate-databasecommandincodefirstmigration 1 IsItpossibletorunacustomseedingmethodfromthepackagemanagerconsole? 1 EFCore2.0MigrationsNotRecognizedbyPackageManagerConsole HotNetworkQuestions WhathadEstherdonein"TheBellJar"bySylviaPlath? Workplaceidiomfor"beiGelegenheit"-ordertodoeventually,butdonotprovidepriority Whydoesn'ttheMBRS1100SchottkydiodehaveanexponentialI/Vcharacteristic? LyX:HowcanIinputasecondparagraphinanenumerateitem? WillIgetdeniedentryafterIremovedavisasticker?Ismypassportdamaged? InD&D3.5,canafamiliarbetemporarilydismissed? Interpretinganegativeself-evaluationofahighperformer Doyoupayforthebreakfastinadvance? DoestheDemocraticPartyofficiallysupportrepealingtheSecondAmendment? Levinson'salgorithmandQRdecompositionforcomplexleast-squaresFIRdesign Howtosimplifyapurefunction? HowIcanremoveautoincrementfromaPrimarykeyinpostgresql? rename(Perl)-tryingtorenumberalistoffiles,startingatacertainvalue Theunusualphrasing"verb+the+comparativeadjective"intheLordoftheRingsnovels Howtoelegantlyimplementthisoneusefulobject-orientedfeatureinMathematica? WhyareRussiancombatantsinUkraineconsideredsoldiersratherthanterrorists? ConvertanintegertoIEEE754float Howtoremovetikznode? Howdouncomputablenumbersrelatetouncomputablefunctions? Howdoparty-listsystemsaccommodateindependentcandidates? Adecimal-basedunitoftime Whyistherealotofcurrentvariationattheoutputofabuckwhenabatteryisconnectedattheoutput? Alternativeversionsofbreathing? Myfavoriteanimalisa-singularandpluralform morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. default Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?