【问题标题】:How to correctly use DBContext/EF in a winform application?如何在 winform 应用程序中正确使用 DBContext/EF?
【发布时间】:2017-07-17 16:40:56
【问题描述】:

winforms 应用程序中关于 EF 的信息不多。在 this msdn page,我们发现:

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

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

using (var context = new MyAppContext()) 
{     
    // Perform operations 
}

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

正确吗?

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

【问题讨论】:

  • 这里有一个类似的线程:stackoverflow.com/questions/20216147/…。你基本上可以走几种方式。您可以每次都指定它,并使用从配置文件或其他方式获取的全局变量来更改它。或者,您可以为 X 个环境创建一个连接字符串,然后使用一个变量或其他位置来引用您想要的内容。最终,大多数时候我看到有人在部署时更改了他们的配置文件,因此它对于您的环境来说是静态的。

标签: c# winforms entity-framework dbcontext


【解决方案1】:

我相信对于需要包含的任何模型,每个表单都需要一个上下文实例。这是我刚刚参加的课程 (Entity Framework in Depth: The Complete Guide) 的表单背后的代码,它位于 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();
        }
    }
}

【讨论】:

    猜你喜欢
    • 2019-10-23
    • 2014-02-09
    • 2018-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多