简体   繁体   English

使用实体框架在WPF MVVM中进行验证

[英]Validation in WPF MVVM with Entity Framework

I'm writing a WPF MVVM Light app using Visual Studio 2015. The data has been brought in using Entity Framework 6, using database-first to generate the models. 我正在使用Visual Studio 2015编写WPF MVVM Light应用程序。数据已经使用Entity Framework 6引入,使用数据库优先生成模型。 In my MainViewModel.cs file, I'd like to validate the data before doing a SaveChanges() . 在我的MainViewModel.cs文件中,我想在执行SaveChanges()之前验证数据。

The examples I've seen talk about adding annotations to models (for example, this ); 我见过的例子谈到了为模型添加注释(例如, 这个 ); however, I'm using auto-generated Entity Framework models. 但是,我正在使用自动生成的Entity Framework模型。 And my ViewModels reference ObservableCollection<Employee> objects -- nothing references fields directly, so that I can put annotations on them. 我的ViewModels引用ObservableCollection<Employee>对象 - 没有任何东西直接引用字段,因此我可以在它们上添加注释。

Here is the SearchResults property, which holds the results returned from EF: 这是SearchResults属性,它保存从EF返回的结果:

private ObservableCollection<Employee> _searchResults;
public ObservableCollection<Employee> SearchResults
{
    get { return _searchResults; }
    set
    {
        if (_searchResults == value) return;

        _searchResults = value;
        RaisePropertyChanged("SearchResults");
    }
}

The SearchResults gets populated after a search and are bound to a DataGrid: SearchResults在搜索后填充并绑定到DataGrid:

var query = Context.Employees.AsQueryable();

// Build query here...

SearchResults = new ObservableCollection<Employee>(query.ToList());

The user clicks a row on the DataGrid and we show the details for them to update. 用户单击DataGrid上的一行,我们会显示要更新的详细信息。 They can then hit the Save button. 然后他们可以点击“保存”按钮。 But we want to validate the fields in each Employee before performing Context.SaveChanges() . 但是我们想在执行Context.SaveChanges()之前验证每个Employee的字段。

Here's the pertinent area of the partial class Employee , auto-generated by Entity Framework: 这是Entity Framework自动生成的分类Employee的相关区域:

public int employeeID { get; set; }
public int securityID { get; set; }
public string firstName { get; set; }
public string middleName { get; set; }
public string lastName { get; set; }
public string suffix { get; set; }
public string job { get; set; }
public string organizationalUnit { get; set; }
public string costCenter { get; set; }
public string notes { get; set; }
public System.DateTime createdDate { get; set; }

For example, the securityID must not be blank and it must be an int , while firstName and lastName are required, etc. How do you accomplish this validation and show errors to the user? 例如, securityID不能为空,它必须是int ,而firstNamelastName是必需的,等等。如何完成此验证并向用户显示错误?

I assume when you show user the details you are using TextBox es (You can apply the same solution for other controls). 我假设当您向用户显示您正在使用TextBox es的详细信息时(您可以为其他控件应用相同的解决方案)。

Instead of validating data after the user changes the properties of Employee , just validate beforehand and don't even change the properties if they are invalid. 在用户更改Employee的属性之后,不要验证数据,只需事先验证,如果属性无效,甚至不更改属性。

You can do this easily with ValidationRule class. 您可以使用ValidationRule类轻松完成此操作。 For example: 例如:

<ListBox ItemsSource="{Binding Employees}" Name="ListBoxEmployees">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Name}"></TextBlock>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
<TextBox>
    <TextBox.Text>
        <Binding ElementName="ListBoxEmployees" Path="SelectedItem.Name" UpdateSourceTrigger="PropertyChanged">
            <Binding.ValidationRules>
                <stackOverflow:NotEmptyStringValidationRule/>
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
</TextBox>

and the validation rule: 和验证规则:

public class NotEmptyStringValidationRule : ValidationRule
{
    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        string s = value as string;
        if (String.IsNullOrEmpty(s))
        {
            return new ValidationResult(false, "Field cannot be empty.");
        }

        return ValidationResult.ValidResult;
    }
}

Also you can disable the Save button when any of the validation rules fail. 此外,您可以在任何验证规则失败时禁用“保存”按钮。

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

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