当我声明可以为空或 null 时,我一直收到 "db context null",我该如何解决?

I keep getting "db context null" when ive stated that its okay to be empthy or null, how can i fix it?

我想让我在数据库中的产品显示在我的网页上(我目前有 0 个),我的代码是,

这是我的 DVDDataSQL class:

public IEnumerable<DVD> GetDVDs(string name = null)
    {
        var param = !string.IsNullOrEmpty(name) ? $"{name}%" : name;
        return scandiwebTestDbContext.DVDs.Where(r => string.IsNullOrEmpty(name) || EF.Functions.Like(r.Name, param)).ToList();
    }

这是在我的 Idvddata 界面中:

public interface IDVDData
{
    DVD GetProductById(int DvdId);
    DVD Create(DVD Dvd);
    int Commit();
    DVD Delete(int DvdId);
   
    IEnumerable<DVD> GetDVDs(string name = null);
  
}

这是我的数据库 class:

public class ScandiwebTestDbContext : DbContext
{
    public ScandiwebTestDbContext(DbContextOptions<ScandiwebTestDbContext> options) : base(options)
    {

    }

   
    public DbSet<DVD> DVDs { get; set; }
    public DbSet<Book> Books { get; set; }
    public DbSet<Furniture> Furnitures {get;set;}
}

我在启动程序中添加了这个

public void ConfigureServices(IServiceCollection services)
    {
        services.AddRazorPages();
        services.AddMvc();
        services.AddDbContext<ScandiwebTestDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ScandiDb")));
        services.AddScoped<IDVDData, DVDDataSQL>();
        services.AddScoped<IBookData, BookDataSQL>();
        services.AddScoped<IFurnitureData, FurnitureDataSQL>();
    }

我明确表示可以为 null 或为空,但它会抛出一个异常,即它的 null 以太方式。我以前从来没有遇到过这个问题,而且我总是这样做,我不确定我是否遗漏了什么?

你必须注入你的 dbcontext,像这样

public class DVDData : IDVDData
{

private readonly ScandiwebTestDbContext _scandiwebTestDbContext
public  DVDData (ScandiwebTestDbContext scandiwebTestDbContext)
{
   _scandiwebTestDbContext=scandiwebTestDbContext;
}

.....
public IEnumerable<DVD> GetDVDs(string name = null)
    {
        var param = !string.IsNullOrEmpty(name) ? $"{name}%" : name;
        return _scandiwebTestDbContext.DVDs.Where(r => string.IsNullOrEmpty(name) || EF.Functions.Like(r.Name, param)).ToList();
    }

}