系统。InvalidOperationException:无法解析类型为"Microsoft"的服务。EntityFrameworkCore。DbSet"1[Entities.Product]"试图激活"Drin。数据存储库。GenericRepository `1[Entitys.Product]'.
我在尝试执行控制器方法时收到此错误
public class SampleDbContext : DbContext
{
public SampleDbContext(DbContextOptions<SampleDbContext> options) : base(options) {
}
public DbSet<Category> Category { get; set; }
public DbSet<Product> Product { get; set; }
public DbSet<ProductFeature> ProductFeature { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
builder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());
builder.Entity<ProductFeature>().HasData(
new ProductFeature { Id = 1, Colour = "Black", Weight = 40, ProductId = 1 },
new ProductFeature { Id = 2, Colour = "Blue", Weight = 10, ProductId = 2 });
base.OnModelCreating(builder);
}
}
类似的程序.cs代码文件
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddScoped<IUnitOfWork, UnitOfWork>();
builder.Services.AddScoped(typeof(IGenericRepository<>), typeof(GenericRepository<>));
builder.Services.AddScoped(typeof(IService<>), typeof(Service<>));
builder.Services.AddAutoMapper(typeof(MapProfile));
builder.Services.AddDbContext<SampleDbContext>(x =>
{
x.UseSqlServer(builder.Configuration.GetConnectionString("DevConnection"), options =>
{
options.MigrationsAssembly(Assembly.GetAssembly(typeof(SampleDbContext)).GetName().Name);
});
});
GenericRepository也类似:
public class GenericRepository<T> : IGenericRepository<T> where T : class
{
private readonly SampleDbContext context;
private readonly DbSet<T> dbSet;
public GenericRepository(SampleDbContext context, DbSet<T> dbSet)
{
this.context = context;
this.dbSet = context.Set<T>();
}
public async Task AddAsync(T entity)
{
await dbSet.AddAsync(entity);
}
}
您似乎正在将DbSet<Product>
注入存储库。通常的方法是使用AddDbContext
或AddDbContextFactory
仅在DI中注册上下文,并在存储库中解析上下文:
public class SomeClassDependingOnDb
{
private readonly SomeAppDbContext _context;
public class SomeClassDependingOnDb(SomeAppDbContext context) => _context = context;
...
}
然后您可以使用它通过Set<TEntity>
方法-_context.Set<TEntity>
通过泛型类型访问特定的DbSet
(如果持有方法/类型是TEntity
的泛型(。
查看更多文档:
- DbContext生存期、配置和初始化
- ASP。NET核心
UPD
考虑到之前写的所有内容,您的repo应该是这样的(删除DbSet<T> dbSet
参数(:
public class GenericRepository<T> : IGenericRepository<T> where T : class
{
private readonly SampleDbContext context;
private readonly DbSet<T> dbSet;
public GenericRepository(SampleDbContext context)
{
this.context = context;
this.dbSet = context.Set<T>();
}
public async Task AddAsync(T entity)
{
await dbSet.AddAsync(entity);
}
}