1

I am using entity framework 6, .Net framework 4 and code first.

I am able to get the validation errors by using GetValidationResult method. But I was not able to show the validation message like the one given in the below image. How to achieve this?

enter image description here

My Code:

<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>

Code Behind:

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

    }
    else
    {

    }
}
0

1 Answer 1

4

You should decorate your code first POCO classes.

This can look like:

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

You can then get the specific errors using an extension method like this:

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;
}

You could then use the list as a property to populate a validation template in your view. In your example this could occur on the 'Save' click event.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.