【问题标题】: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())。
正确吗?
如果是,我如何在运行时更改整个应用程序的数据库?
【问题讨论】:
标签:
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();
}
}
}