Working with Database First Approach in Entity Framework Core
文章推薦指數: 80 %
So for the demo purposes I am using an class library project and an ASP.NET Core Web API project, and I am using WideWorldImporters database ...
AboutProjectsArchivesSearchFeedWorkingwithDatabaseFirstApproachinEntityFrameworkCoreJuly05,2022byAnurajEstimatedreadtime:2minsAspNetCoreEFCoreThispostisaboutworkingwithDatabaseFirstapproachinEntityFrameworkCore.ThisapproachisusefulinscenariowherewealreadygotaDatabaseandweneedtogeneratemodelanddbcontextclasses.SoforthedemopurposesIamusinganclasslibraryprojectandanASP.NETCoreWebAPIproject,andIamusingWideWorldImportersdatabasefromSQLServer.SofirstIcreatedasolutionfile,thewebapiprojectandfinallyaclasslibraryproject.AndIaddedthewebapiandclasslibraryprojectstothesolution.Andaddedthereferenceofclasslibrarytotheapiproject.Iamusing.NETCLItoolstodothis.HerearethecommandsIexecuted.dotnetnewsln
dotnetnewwebapi-oApi
dotnetnewclasslib-oData
dotnetslnadd.\Api\
dotnetslnadd.\Data\
dotnetaddreference..\Data\Data.csprojNexttoscaffoldtheentitiesanddatabasecontextweneedaddtwonugetpackages(Microsoft.EntityFrameworkCore.DesignandMicrosoft.EntityFrameworkCore.SqlServer)totheclasslibrary.dotnetaddpackageMicrosoft.EntityFrameworkCore.Design
dotnetaddpackageMicrosoft.EntityFrameworkCore.SqlServerNowwearereadytoexecutethescaffoldcommand-whichwillgeneratemodelclassesanddatabasecontext.Weareusingthedotneteftoolforscaffolding.Ifyou’renotinstalledtheEFCoretool,youneedtoinstallit.Hereisthecommandusingthedotneteftool.dotnetefdbcontextscaffold"Server=LOCALHOST;UserId=sa;Password=Password@123;Database=WideWorldImporters"Microsoft.EntityFrameworkCore.SqlServerHereisthecommandexecutionOncethecommandexecutedyouwillbeabletoseetheentitiesanddatabasecontextclassesaspartoftheclasslibraryproject.RightnowtheDatabasecontextfilecontainstheconnectionstringinsidetheOnConfiguringmethod.protectedoverridevoidOnConfiguring(DbContextOptionsBuilderoptionsBuilder)
{
if(!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer("Server=LOCALHOST;UserId=sa;Password=Password@123;Database=WideWorldImporters");
}
}WeneedtoremovethecodesinceweareusingthislibraryintheASP.NETWebAPI.NextweneedtomodifythewebapiprojectandaddreferenceofMicrosoft.EntityFrameworkCore.SqlServer.Onceitisdone,weneedtomodifytheprogram.csfilelikethis.builder.Services
.AddDbContext
延伸文章資訊
- 1Database First - EF6 | Microsoft Learn
- 2Entity Framework - Database First Approach - Tutorialspoint
- 3Database First - 資料庫優先- EF6 - Microsoft Learn
Entity Framework 6 中的資料庫優先.
- 4Microsoft Claims Entity Framework Core 7 Faster When Saving Changes
- 5[ASP.net Core] 使用Entity Framework Core Database First方式 ...
access data through Entity Framework Core Database First in separate classlibrary project. 嚴格來說,標...