简体   繁体   English

设计器问题+实体框架(WPF MVVM)

[英]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. 在后台,这是一个WPF项目,它使用实体框架,当运行良好时,只是设计器会产生以下错误。

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. 未处理的异常在配置中找不到指定的命名连接,或者不打算与EntityClient提供程序一起使用,或者无效。

I have coped the connection string to the UI but this is still a problem 我已将连接字符串处理到UI,但这仍然是一个问题

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. 您的代码在实例化时试图访问您的数据,因此Entity Framework代码在错误的位置查找您的连接字符串。 The solution is to not do that at design mode. 解决方案是在设计模式下不要这样做。

The naive method is to check DesignerProperties.GetIsInDesignMode . 天真的方法是检查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. 这并不是真正的MVVM,因为您必须在视图模型中进行检查,并将UI代码注入视图模型。

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. 您可以hold着鼻子做它(快速又脏),创建一个可注射的接口,将其从ViewModel中提取出来,这是默认情况下检查DependencyProperty的实现,或者您捕获异常并优雅地吞下它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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