Ramesh Durai
Ramesh Durai

Reputation: 2686

Implement data validation in entity framework code first

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
    {

    }
}

Upvotes: 1

Views: 1559

Answers (1)

calebboyd
calebboyd

Reputation: 5753

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.

Upvotes: 4

Related Questions