首先在实体框架代码中实施数据验证 [英] Implement data validation in entity framework code first

查看:43
本文介绍了首先在实体框架代码中实施数据验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我首先使用实体​​框架6,.Net框架4和代码.

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

我能够通过使用 GetValidationResult 方法来获得验证错误.但是我无法像下图所示那样显示验证消息.如何实现呢?

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?

我的代码:

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

    }
}

推荐答案

您应该首先在POCO类中修饰代码.

You should decorate your code first POCO classes.

这看起来像:

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

这篇关于首先在实体框架代码中实施数据验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆