سؤال

I'm using C# + WPF + MvvmLight to write a C/S client.In this program,I will connect to MySQL databases to view and modify tables.I know how to connect to MySQL database in C#,what I'm wondering about is how to maintain my connection to MySQL dbs.As far as I'm concerned,I come about two methods:

  • Declare a global MySqlConnection type variable
  • Save my connection string in a config file and load it whenever needed.

Whats the pros and cons of these two methods?Any other sollutions would be mostly appreciated as well.

هل كانت مفيدة؟

المحلول

There are different ways to handle this. Probably the most common in WPF is to let your viewmodel handle manipulating the database (which is part of your model), typically through some sort of repository or facade. If you check out the reference MVVM WPF application you can see a simple version of this in action, eg:

public class CustomerViewModel : WorkspaceViewModel, IDataErrorInfo
{
    ...
    public void Save()
    {
        if (!_customer.IsValid)
            throw new InvalidOperationException(Strings.CustomerViewModel_Exception_CannotSave);

        if (this.IsNewCustomer)
            _customerRepository.AddCustomer(_customer);

        base.OnPropertyChanged("DisplayName");
    }

In this pattern, the repository object will usually maintain the database connection, but it's the viewmodel code that calls into the repository. And of course, you can replace that megalithic repository with a full-fledged DAL depending on your needs.

نصائح أخرى

Mum...I realized later that C# does not have a global type,but you can still use some trick.

For instance,

Add this reference first,

using Microsoft.Practices.ServiceLocation;

then get the current instance of your interested ViewModel

MainViewModel mainViewModelInstance = ServiceLocator.Current.GetInstance<MainViewModel>();

Now,you can do nearly every thing,like passing properties,for instance,without having to implement an instance of ViewModel.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top