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

问题描述:

在winforms应用程序中没有太多关于EF的信息。在T his msdn page,我们发现:如何在Winform应用程序中正确使用DBContext/EF?

当的Windows Presentation Foundation(WPF)或Windows工作 表格,每个表格使用上下文实例。这使您可以使用上下文提供的变更跟踪功能 。

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

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

,但我应该在每个形式加载时间创建一个新的MyAppContext并释放它时,形式是关闭(和在之前可选地为SaveChange())。

它正确吗?

如果是的话,我怎么能在运行时更改我的数据库为我的整个应用程序?

+1

这里有一个类似的线程:https://stackoverflow.com/questions/20216147/entity-framework-change-connection-at-runtime。你基本上可以走几条路。您可以每次指定它,并具有从配置文件获取的全局变量或其他方式来更改它。或者,您可以为X个环境创建一个连接字符串,然后使用变量或其他位置来指向您想要的指针。最终,大多数时候我看到有人在部署时更改其配置文件,因此对于您的环境而言它是静态的。 – djangojazz

我相信你需要为每个表单需要一个上下文实例,你需要包含任何模型。这是来自我刚刚参加的课程的一个表格背后的代码(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(); 
     } 
    } 
}