将 DbContext 与依赖注入一起使用

Using DbContext with dependency injection

我在 MVVM 架构中构建 WPF 应用程序。按下按钮应该给我 DataGrid 数据库中的数据。应用程序正确构建并且我可以启动它但是当我按下按钮时我得到“对象引用[...]”并且关于 dbContext 的信息为空。

下面是一些代码:

AuctionDbContext.cs

 public class AuctionDbContext: DbContext
    {

        public AuctionDbContext(DbContextOptions<AuctionDbContext> options): base(options)
        {

            /* Database.EnsureCreated();*/
        }

        public DbSet<Auction> Auctions { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {            
            base.OnModelCreating(modelBuilder);
        }

App.cs

public partial class App : Application
    {
        private ServiceProvider serviceProvider;
        private DbCreator dbCreator = new DbCreator();


        public App()
        {
            ServiceCollection services = new ServiceCollection();

            services.AddDbContext<AuctionDbContext>(option =>
            {
                option.UseSqlite("Data Source = " + DbCreator.DATABASE_FILE_PATH);
            });

            services.AddSingleton<MainWindow>();

            serviceProvider = services.BuildServiceProvider();

        }

        private void OnStartup(object sender, StartupEventArgs e)
        {
            dbCreator.createDbFile();
            dbCreator.createConnectionToDatabase();
            dbCreator.createTable();
            dbCreator.fillTable();

            var mainWindow = serviceProvider.GetService<MainWindow>();
            mainWindow.Show();

        }
        
    }
}

MainWindow.cs

public partial class MainWindow : Window
{
    AuctionDbContext dbContext;
    public MainWindow()
    {
        InitializeComponent();
    }

    private void MarketMenu_Clicked(object sender, RoutedEventArgs e)
    {
        DataContext = new MarketViewModel(dbContext);
    }
}

MarketViewModel.cs

   public class MarketViewModel
    {
        AuctionDbContext dbContext;
        MarketView marketView = new MarketView();

        public MarketViewModel(AuctionDbContext dbContext)
        {
            this.dbContext = dbContext;
            GetAuctions();
        }

        private void GetAuctions()
        {
            marketView.AuctionDG.ItemsSource = dbContext.Auctions.ToList(); /* Here I got error */
        }
    }
}

我使用了这个文档,没有发现任何错误:( https://docs.microsoft.com/en-us/ef/core/miscellaneous/configuring-dbcontext

以前,当我在 mainWindow class 中拥有所有内容时,一切正常,但那是 PoC。当我将项目重构为 MVVM 时出了点问题。我花了几个小时寻找解决方案但没有成功。

如果有帮助,这是我在 GitHub https://github.com/BElluu/EUTool 上的回购协议。查看分支:1-refactor-to-mvvm 因为 master 已经过时了:)

您似乎没有初始化 MainWindow 中的 dbContext 字段:

public partial class MainWindow : Window
{
    AuctionDbContext dbContext;
    public MainWindow(AuctionDbContext dbContext)
    {
        this.dbContext = dbContext;
        InitializeComponent();
    }

    private void MarketMenu_Clicked(object sender, RoutedEventArgs e)
    {
        DataContext = new MarketViewModel(dbContext);
    }
}