winforms应用程序中没有太多关于EF的信息。在此 msdn 页面上,我们发现:
使用 Windows Presentation Foundation (WPF( 或 Windows 时 表单,每个表单使用一个上下文实例。这使您可以使用 上下文提供的更改跟踪功能。
所以我假设我不应该使用:
using (var context = new MyAppContext())
{
// Perform operations
}
但我应该在每个表单的加载时创建一个新MyAppContext
,并在表单关闭时(以及可选的SaveChange()
之前(释放它。
正确吗?
如果是,如何在运行时更改整个应用程序的数据库?
我相信对于需要包含的任何模型,每个表单都需要一个上下文实例。下面是我刚刚学习的课程(深入的实体框架:完整指南(中的窗体背后的代码,该窗体位于 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();
}
}
}