如何在winform应用程序中正确使用DBContext/EF?

Mal*_*ick 5 c# entity-framework winforms dbcontext

winforms应用程序中关于EF的信息并不多。在他的 msdn 页面上,我们发现:

使用 Windows Presentation Foundation (WPF) 或 Windows 窗体时,请为每个窗体使用一个上下文实例。这使您可以使用上下文提供的更改跟踪功能。

所以我认为我不应该使用:

using (var context = new MyAppContext()) 
{     
    // Perform operations 
}
Run Code Online (Sandbox Code Playgroud)

但我应该在每个MyAppContext表单的加载时创建一个新的,并在表单关闭时(也可以选择之前)释放它。SaveChange()

这是对的吗 ?

如果是,我如何在运行时更改整个应用程序的数据库?

小智 2

我相信您需要为您需要包含的任何模型提供每个表单的上下文实例。下面是我刚刚参加的课程(实体框架深入:完整指南)中的表单背后的代码,它位于 WPF 表单后面。我希望这有帮助!

using PlutoDesktop.Core.Domain;
using PlutoDesktop.Persistence;
using System;
using System.Data.Entity;
using System.Windows;

namespace PlutoDesktop
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private PlutoContext _context = new PlutoContext();

        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            System.Windows.Data.CollectionViewSource courseViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("courseViewSource")));

            _context.Courses.Include(c => c.Author).Load();

            courseViewSource.Source = _context.Courses.Local;
        }

        protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
            base.OnClosing(e);

            _context.Dispose();
        }

        private void AddCourse_Click(object sender, RoutedEventArgs e)
        {
            _context.Courses.Add(new Course
            {
                AuthorId = 1,
                Name = "New Course at " + DateTime.Now.ToShortDateString(),
                Description = "Description",
                FullPrice = 49,
                Level = 1

            });

            _context.SaveChanges();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)