EF Core Database-First Tutorial for .NET Core - Devart

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

Entity Framework Core supports Database-First approach via the Scaffold-DbContext command of Package Manager Console. This command scaffolds a DbContext and ...  dotConnectforPostgreSQLDocumentation EntityFrameworkCoreDatabase-FirstTutorialfor.NETCore [email protected] EntityFrameworkCoresupportsDatabase-FirstapproachviatheScaffold-DbContextcommandofPackageManagerConsole.ThiscommandscaffoldsaDbContextandentitytypeclassesforaspecifieddatabase. Thistutorialshowshowtocreateasimpleconsoleapplication, poweredbyEntityFrameworkCoreandusingDatabase-Firstapproach.Inlessthan10minutesyouwillhavea ready-to-usedataaccesslayerforyourbusinessobjects. Thistutorialisfor.NETCore.ForFull.NETFrameworkseeEntityFrameworkCoreDatabase-FirstTutorialforFull.NETFramework. Requirements Thistutorialrequiresthefollowing: VisualStudio2017orhigher(forEntityFrameworkCore3.1-VisualStudio2019) IfyouwanttouseEntityFrameworkCore2.2-.NETCoreSDK2.2.ForEntityFrameworkCore3.1-.NETCoreSDK3.0 LatestversionofNuGetPackageManager LatestversionofWindowsPowerShell Wewillusethetables,wehavecreatedintheCreatingDatabaseObjectsandInsertingDataIntoTablestutorials.Inthistutorialitisassumedthatyoualreadyhavethedatabaseobjectscreated.Ifyouhaven'tcreatedthemyet,pleasedoitbeforestartingthistutorial. CreatingNewProject OpenVisualStudio OntheFilemenupointtoNewandthenclickProject.TheNewProjectdialogboxwillopen. OntheleftsideofthedialogboxselectInstalled->VisualC#->.NETCore. OntherightsideofthedialogboxselectConsoleApp. Entertheprojectnameandlocationifnecessary. ClickOK.Anewprojectwillbecreated. InstallingNuGetPackages Afterwecreatedanewproject,weneedtoaddthenecessaryNuGetpackagestoit. Nowlet'sinstallthenecessarypackages: OntheToolsmenupointtoNuGetPackageManagerandthenclickPackageManagerConsole. ForEntityFrameworkCore5,runthefollowingcommandinthePackageManagerConsole: Install-PackageMicrosoft.EntityFrameworkCore.Tools ForEntityFrameworkCore3.1,runthefollowingcommandinthePackageManagerConsole: Install-PackageMicrosoft.EntityFrameworkCore.Tools-Version3.1.10 ForEntityFrameworkCore2.2,runthefollowingcommandinthePackageManagerConsole: Install-PackageMicrosoft.EntityFrameworkCore.Tools-Version2.2.6 ForEntityFrameworkCore1.1,thecommandwillbethefollowing: Install-PackageMicrosoft.EntityFrameworkCore.Tools-Version1.1.5 ForEntityFrameworkCore3.1or5.0runthefollowingcommandinthePackageManagerConsole: Install-PackageDevart.Data.PostgreSql.EFCore ForEntityFrameworkCore1.1,thecommandwillbethefollowing: Install-PackageDevart.Data.PostgreSql.EFCore.Design NotethatthedotConnectforPostgreSQLassemblyforEntityFrameworkCore2.2isnotavailableviaNuGetpackagesanymore.ItisinstalledbythedotConnectforPostgreSQLinstallertothe\Entity\EFCore2\netstandard2.0\subfolderofthedotConnectforPostgreSQLinstallationfolder. CreatingaModelFromtheDatabase ForEntityFrameworkCore,creatingamodelfromthedatabaseisaseasyasenteringtheScaffold-DbContextcommandwithaconnectionstringandaproviderasparameters.Forexample,youcanrunthefollowingcommandinthePackageManagerConsole: Scaffold-DbContext"host=server;database=test;userid=postgres;"Devart.Data.PostgreSql.Entity.EFCore Ifyouhaveothertablesinyourdatabase,youmayuseadditionalparameters--Schemasand-Tables-tofilterthelistofschemasand/ortablesthatareaddedtothemodel.Forexample,youcanusethefollowingcommand: Scaffold-DbContext"host=server;database=test;userid=postgres;"Devart.Data.PostgreSql.Entity.EFCore-Tablesdept,emp Astheresult,acontextclassandentityclassesaregenerated,basedontheDeptandEmptables. C#csharpCopyCode usingSystem; usingSystem.Collections.Generic; namespaceConsoleApplication1 { publicpartialclassDept { publicDept() { Emp=newHashSet(); } publicintDeptno{get;set;} publicstringDname{get;set;} publicstringLoc{get;set;} publicvirtualICollectionEmp{get;set;} } } C#csharpCopyCode usingSystem; usingSystem.Collections.Generic; namespaceConsoleApplication1 { publicpartialclassEmp { publicintEmpno{get;set;} publicstringEname{get;set;} publicstringJob{get;set;} publicintMgr{get;set;} publicDateTimeHiredate{get;set;} publicdoubleSal{get;set;} publicdoubleComm{get;set;} publicintDeptno{get;set;} publicvirtualDeptDeptnoNavigation{get;set;} } } Entityclassesarejustsimpleclasses,representingthedata,storedinthedatabase. Thecontextrepresentsasessionwiththedatabaseandallowsyoutoqueryandsaveinstancesoftheentityclasses. C#csharpCopyCode usingSystem; usingMicrosoft.EntityFrameworkCore; usingMicrosoft.EntityFrameworkCore.Metadata; namespaceConsoleApplication1 { publicpartialclassModelContext:DbContext { publicvirtualDbSetDept{get;set;} publicvirtualDbSetEmp{get;set;} protectedoverridevoidOnConfiguring(DbContextOptionsBuilderoptionsBuilder) { #warningToprotectpotentiallysensitiveinformationinyourconnectionstring,youshouldmoveitoutofsourcecode.Seehttp://go.microsoft.com/fwlink/?LinkId=723263forguidanceonstoringconnectionstrings. optionsBuilder.UsePostgreSql(@"host=server;database=test;userid=postgres;"); } protectedoverridevoidOnModelCreating(ModelBuildermodelBuilder) { modelBuilder.Entity(entity=> { entity.HasKey(e=>e.Deptno) .HasName(""); entity.ToTable("DEPT","public"); entity.Property(e=>e.Deptno).HasColumnName("DEPTNO"); entity.Property(e=>e.Dname) .HasColumnName("DNAME") .HasColumnType("varchar") .HasMaxLength(14); entity.Property(e=>e.Loc) .HasColumnName("LOC") .HasColumnType("varchar") .HasMaxLength(13); }); modelBuilder.Entity(entity=> { entity.HasKey(e=>e.Empno) .HasName(""); entity.ToTable("EMP","public"); entity.Property(e=>e.Empno).HasColumnName("EMPNO"); entity.Property(e=>e.Comm) .HasColumnName("COMM") .HasColumnType("double"); entity.Property(e=>e.Deptno).HasColumnName("DEPTNO"); entity.Property(e=>e.Ename) .HasColumnName("ENAME") .HasColumnType("varchar") .HasMaxLength(10); entity.Property(e=>e.Hiredate) .HasColumnName("HIREDATE") .HasColumnType("date"); entity.Property(e=>e.Job) .HasColumnName("JOB") .HasColumnType("varchar") .HasMaxLength(9); entity.Property(e=>e.Mgr).HasColumnName("MGR"); entity.Property(e=>e.Sal) .HasColumnName("SAL"); entity.HasOne(d=>d.DeptnoNavigation) .WithMany(p=>p.Emp) .HasForeignKey(d=>d.Deptno) .HasConstraintName("emp_deptno_fkey"); }); } } } Herewemaycommentordeletethewarningabouttheconnectionstring.Afterthiswecanstartusingourmodeltoretrieveandmodifydata. UsingModel OpenyourProgram.csfileandpastethefollowingcodeinsteadoftheMainfunction: C#csharpCopyCode staticvoidMain(string[]args) { using(vardb=newModelContext()) { //Creatinganewdepartmentandsavingittothedatabase varnewDept=newDept(); newDept.Deptno=60; newDept.Dname="Development"; newDept.Loc="Houston"; db.Dept.Add(newDept); varcount=db.SaveChanges(); Console.WriteLine("{0}recordssavedtodatabase",count); //Retrievinganddisplayingdata Console.WriteLine(); Console.WriteLine("Alldepartmentsinthedatabase:"); foreach(vardeptindb.Dept) { Console.WriteLine("{0}|{1}",dept.Dname,dept.Loc); } } } Afterthis,ontheDebugmenu,clickRunwithoutdebugging. SeeAlso Compatibility   ©2003-2022Devart.Allrightsreserved.



請為這篇文章評分?