简体   繁体   中英

Designer Issue + Entity Framework (WPF MVVM)

Background, this is a WPF project that uses the entity framework which when run works fine, it is just the designer which gives the following error.

Unhandled exception The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid.

I have coped the connection string to the UI but this is still a problem

I have the following binding

   DataContext="{Binding Source={x:Static ViewModel:ViewModelLocator.MainWindowViewModelStatic}}"

Which relates to a class which initialises

     new MainWindowViewModel(new UIDataProvider());

which has the following

    private readonly IUIDataProvider _dataProvider;

    private IList<Customer> _customers;

    public IList<Customer> Customers
    {
        get
        {
            if (_customers == null)
            {
                GetCustomers();
            }
            return _customers;
        }
    }

    public MainWindowViewModel(IUIDataProvider dataProvider)
    {
        _dataProvider = dataProvider;

        Tools = new ObservableCollection<ToolViewModel>();
        Tools.Add(new AToolViewModel());
        Tools.Add(new BToolViewModel());
    }


    private void GetCustomers()
    {
        _customers = _dataProvider.GetCustomers();
    }

The designer actually instantiates your code at design time. Your code is, upon instantiation, attempting to access your data, and so the Entity Framework code is looking in the wrong place for your connection string. The solution is to not do that at design mode.

The naive method is to check DesignerProperties.GetIsInDesignMode . This isn't really MVVM, as you have to check this in your view model, and that injects UI code into your view model.

What's the solution? You can just hold your nose and do it (quick and dirty), create an inject-able interface which abstracts this check from your ViewModel, which is by-default an implementation that checks that DependencyProperty, or you catch the exception and swallow it gracefully.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM