2013-10-03 175 views
1

我首先使用实体​​框架6,.Net框架4和代码。首先在实体框架代码中实现数据验证

我能够通过使用GetValidationResult方法得到验证错误。但我无法显示验证信息,如下图所示。如何实现这一目标?

enter image description here

我的代码:

<Label Content="Name" /> 
<Grid Grid.Row="0" Grid.Column="2"> 
    <Grid.ColumnDefinitions> 
     <ColumnDefinition Width="Auto" /> 
    </Grid.ColumnDefinitions> 
    <TextBox x:Name="txtName" 
      Width="200" 
      Margin="8,0,0,0" 
      MaxLength="150" 
      Text="{Binding Path=dfc_Name, 
          ValidatesOnDataErrors=True}" /> 
</Grid> 

<Label Grid.Row="4" 
     Grid.Column="0" 
     Content="Description" /> 
<TextBox x:Name="txtDescription" 
     Grid.Row="4" 
     Grid.Column="2" 
     Width="300" 
     Height="80" 
     Margin="8,0,0,0" 
     HorizontalAlignment="Left" 
     VerticalContentAlignment="Top" 
     AcceptsReturn="True" 
     Text="{Binding Path=dfc_Description, 
         ValidatesOnDataErrors=True}" 
     TextWrapping="WrapWithOverflow" /> 
</Grid> 

代码背后:

private readonly Item OItem = new Item(); 
public ItemView() 
{ 
    InitializeComponent(); 
    this.DataContext = OItem; 
    if (context.Entry(OItem).GetValidationResult().IsValid) 
    { 

    } 
    else 
    { 

    } 
} 
+1

您使用的是WPF吗? –

回答

4

你应该先装点你的代码POCO类。

这可以看起来像:

[StringLength(25, ErrorMessage = "Blogger Name must be less than 25 characters", MinimumLength = 1)] 
[Required] 
public string BloggerName{ get; set; } 

然后,您可以使用像这样的扩展方法获得的具体错误:

public static List<System.ComponentModel.DataAnnotations.ValidationResult> GetModelErrors(this object entity) 
{ 
    var errorList= new List<System.ComponentModel.DataAnnotations.ValidationResult>(); 
    System.ComponentModel.DataAnnotations.Validator.TryValidateObject(entity, new ValidationContext(entity,null,null), errorList); 
    return errorList.Count != 0 ? errorList: null; 
} 

然后,您可以使用该列表作为一个属性来验证您的看法的模板。在你的例子中,这可能发生在'保存'点击事件。