2023-10-03 11:49:04
Note : This relates to Entity Framework Core Only.
By default, Entity Framework Core (EF) assumes it resides within the start-up assembly.
This can be a problem because we would like to have a separation of concerns. Generally, the start-up assembly is concerned with providing the UI or API and not data access. Our Repository Assembly should handle that and be referenced by the start-up (Views) assembly, via interface classes, which play the role of contract between Views and Repository.
By default, performing database migrations will not work when EF Core is within an assembly other than the start-up assembly. Carry out the following to fix this:
-
Three packages should be imported into the Repository Assembly, using NuGet Package Manager:
- Microsoft.EntityFrameworkCore.Design
- Microsoft.EntityFrameworkCore.SqlServer
- Microsoft.EntityFrameworkCore.Tools
-
Once installed edit the Repository Assembly .csproj file
- Add the following line to a
<PropertyGroup>
.<GenerateRuntimeConfigurationFiles>True</GenerateRuntimeConfigurationFiles>
- Remove
<PrivateAssets>all</PrivateAssets>
from elements<PackageReference Include="Microsoft.EntityFrameworkCore.Design">
and<PackageReference Include="Microsoft.EntityFrameworkCore.Tools">
- Add the following line to a
Add the override method
OnConfiguring
to your class that inheritsDbContext
.protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer(SampleDbContext.GetConnectionString()); }
- Re-build the application
You will now be able to use EF Package Manager Console commands pointing to the Repository Assembly. For example: