'Unable to resolve service for type Microsoft.EntityFrameworkCore.DbContextOptions
When I want to add controller using ASP.NET Core MVC with views:
This is my DbContext
class:
namespace Infrastructure
{
public class DataContext : DbContext
{
public DataContext(DbContextOptions<DataContext> options) : base(options)
{
}
public DbSet<Owner> owners { get; set; }
public DbSet<ProtoFile> protoFiles { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Owner>().Property(x => x.Id).HasDefaultValueSql("NEWID()");
modelBuilder.Entity<ProtoFile>().Property(x => x.Id).HasDefaultValueSql("NEWID()");
modelBuilder.Entity<Owner>().HasData(
new Owner
{
Id = Guid.NewGuid(),
Avatar = "avatar.jpg",
FullName = "Mohammad AlMohammad AlMahmoud",
Profile = ".NET Full Stack Developer"
});
}
}
}
And I have get this error:
Solution 1:[1]
I solved this problem when I added this code into Datacontext class
protected override void OnConfiguring(DbContextOptionsBuilder DataContext)
{
optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=Test");
}
and it was solved, but after generation the code i have some problem when i run the application , so i remove it and the app worked successfully
from Microsoft docs https://docs.microsoft.com/en-us/ef/core/dbcontext-configuration/
Solution 2:[2]
you have to add this code to your program class (if you use net 6)
builder.Services.AddDbContext<DataContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
or if your are using net 5 or lower, add the same to a startup class
services.AddDbContext<DataContext>(.....
and remove
base.OnModelCreating(modelBuilder);
Solution 3:[3]
I finally fixed it by adding a IDesignTimeDbContextFactory
public class BloggingContextFactory : IDesignTimeDbContextFactory<BloggingContext>
{
public BloggingContext CreateDbContext(string[] args)
{
var optionsBuilder = new DbContextOptionsBuilder<BloggingContext>();
optionsBuilder.UseSqlite("Data Source=blog.db");
return new BloggingContext(optionsBuilder.Options);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Mohammad AlMohammad AlMahmoud |
Solution 2 | |
Solution 3 | Dongdong |