2013-10-03 173 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; 
} 

然後,您可以使用該列表作爲一個屬性來驗證您的看法的模板。在你的例子中,這可能發生在'保存'點擊事件。