【问题标题】:Why do I get error "ArgumentException was thrown on "ViewModelLocator": Cannot create an instance of "ViewModelLocator"为什么我会收到错误“在“ViewModelLocator”上引发了 ArgumentException:无法创建“ViewModelLocator”的实例
【发布时间】:2012-06-05 18:17:21
【问题描述】:

我已经缩小到一个简单的方法,我试图从一个实体模型中填充一个 Observable 集合。我不知道我这样做是否正确。

注意:这似乎是设计者错误。我可以构建并运行程序……它就会出现。

    private ObservableCollection<LessonGroup> lessonGroups;
    public ObservableCollection<LessonGroup> LessonGroups
    {
        get { return LessonGroups; }
        set { lessonGroups = value; RaisePropertyChanged("LessonGroups"); }
    }


    private void GetLessonGroups()
    {
        //this using statement causes ArgumentException
        using (MyEntities ae = new MyEntities())
        {
            foreach (LessonGroup lg in ae.LessonGroups)
            {
                LessonGroups.Add(lg);
            }
        }
    }

异常如下:

The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid.
   at System.Data.EntityClient.EntityConnection.ChangeConnectionString(String newConnectionString)
   at System.Data.EntityClient.EntityConnection..ctor(String connectionString)
   at System.Data.Objects.ObjectContext.CreateEntityConnection(String connectionString)
   at System.Data.Objects.ObjectContext..ctor(String connectionString, String defaultContainerName)
   at IMPACT.ARCTrainer.Model.ARCTrainerEntities..ctor() in C:\Users\Leland\Documents\Visual Studio 2010\Projects\ARCTrainer\Model\ARCTrainer.Designer.cs:line 56
   at IMPACT.ARCTrainer.ViewModel.LessonsViewModel.GetLessonGroups() in C:\Users\Leland\Documents\Visual Studio 2010\Projects\ARCTrainer\ViewModel\LessonsViewModel.cs:line 171
   at IMPACT.ARCTrainer.ViewModel.LessonsViewModel..ctor(ViewModelLocator viewModelLocator) in C:\Users\Leland\Documents\Visual Studio 2010\Projects\ARCTrainer\ViewModel\LessonsViewModel.cs:line 37
   at IMPACT.ARCTrainer.ViewModel.ViewModelLocator..ctor() in C:\Users\Leland\Documents\Visual Studio 2010\Projects\ARCTrainer\ViewModel\ViewModelLocator.cs:line 46

【问题讨论】:

    标签: wpf entity-framework mvvm-light


    【解决方案1】:

    GetLessonGroups 似乎在您的课程 LessonsViewModel 的构造函数中被调用。

    此方法调用 MyEntities,看起来此实体框架上下文与 GUI 项目不是同一个项目。

    要解决您的问题,最好的方法是检查您是否处于设计模式。如果您使用的是 MVVM Light,则可以检查 IsInDesignMode 属性(因此,只有在属性为 false 时才调用 GetLessonGroups 方法)。

    【讨论】:

    • 检查 IsInDesignMode 是个好主意,帮助我摆脱了设计时错误。我仍然很好奇我做错了什么。
    • 您在构造函数中调用了实体框架 DataContext:这将在打开设计器时连接到您的数据库,所以我建议您避免这种情况。
    • 好的,有道理。感谢您的帮助。
    猜你喜欢
    • 2012-01-29
    • 1970-01-01
    • 2021-01-01
    • 2011-08-18
    • 2014-07-31
    • 1970-01-01
    • 2015-07-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多