Implement data validation in entity framework code first

扶醉桌前 提交于 2021-01-28 19:49:26

问题


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
    {

    }
}

回答1:


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.



来源:https://stackoverflow.com/questions/19165816/implement-data-validation-in-entity-framework-code-first

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!