5

There is not much information about EF in winforms applications. On this msdn page, we found :

When working with Windows Presentation Foundation (WPF) or Windows Forms, use a context instance per form. This lets you use change-tracking functionality that context provides.

So I assume that I shouldn't use :

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

but I should create a new MyAppContext at loading time of each form and release it when the form is closing (and optionally SaveChange() before).

Is it correct ?

If yes, how can I change at runtime my database for my whole application ?

Malick
  • 6,252
  • 2
  • 46
  • 59
  • 2
    There is a similar thread to this here: https://stackoverflow.com/questions/20216147/entity-framework-change-connection-at-runtime. You essentially can go a few ways. You can specify it each and every time and have global variable that gets from a config file or other way to change it. Or you can have a connection string for X number of environments and then have a variable or other place to have a pointer reference to what you want. Ultimately most times I see someone change out their config file when doing deploys and so it is static for your environment. – djangojazz Jul 17 '17 at 20:41

1 Answers1

2

I believe you would need a context instance per form for any models you need to include. Here is code behind a form from a course I just took (Entity Framework in Depth: The Complete Guide) that sits behind a WPF form. I hope this helps!

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();
        }
    }
}