【问题标题】:I keep getting "db context null" when ive stated that its okay to be empthy or null, how can i fix it?当我说可以为空或为空时,我不断收到“db context null”,我该如何解决?
【发布时间】:2021-11-12 07:44:19
【问题描述】:

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

这是在我的 DVDDataSQL 类中:

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);
  
}

这是我的数据库类:

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>();
    }

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

【问题讨论】:

  • 你能显示整个代码吗?你如何初始化 scandiwebTestDbContext?
  • 我添加了我连接到 db 类的所有内容

标签: c# database visual-studio exception razor-pages


【解决方案1】:

你必须注入你的 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();
    }

}

【讨论】:

  • 天哪,我怎么会忘记这一点.. 非常感谢!!
  • @David 不客气!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多