Update from OP:
I just wanted to not use any database related package in my API
project for sake of isolation, but after some research I found the
solution : which is to create a DbContextFactory for Creating
Migrations. And the solution I was seeking is impossible, but there is
workaround which is to create the factory for creating the instance of
the dbcontext.
========================
I didn't reproduce your issue in my side. Please kindly compare your codes with mine and have a try.
Firstly, I created a new .net 8 web api project in my VS, and just like what you mentioned. I added connection string in appsettings.json.
"ConnectionStrings": {
"DefaultConnection": "xx"
},
And added DbContext registion in Program.cs
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(connectionString));
What you didn't mentioned in your question is about the nuget packages. Here's what I added in my web api project.
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.8" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.8">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
Then I created the ClassLibrary project. In this project, I created Data folder and Models folder. And my ApplicationDbContext is like below.
namespace ClassLibrary1.Data
{
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<MovieRelease> MovieRel { get; set; }
}
}
This is my Model
namespace ClassLibrary1.Models
{
public class MovieRelease
{
[Key]
public int ReleaseId { get; set; }
public int ReleaseName { get; set; }
}
}
And it requires nuget packages:
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="8.0.8" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.8" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.8" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="8.0.8">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
This is my project structure and my test result.
