使用元数据与实体框架来验证使用数据注释 [英] using Metadata with Entity Framework to validate using Data Annotation

查看:155
本文介绍了使用元数据与实体框架来验证使用数据注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为Product的实体,这是它的声明的一部分:

I have a entity called Product,this is a part of it's declration:

[EdmEntityTypeAttribute(NamespaceName="NorthwindModel", Name="Product")]
[Serializable()]
[DataContractAttribute(IsReference=true)]
public partial class Product : EntityObject
{
    #region Factory Method

    /// <summary>
    /// Create a new Product object.
    /// </summary>
    /// <param name="productID">Initial value of the ProductID property.</param>
    /// <param name="productName">Initial value of the ProductName property.</param>
    /// <param name="discontinued">Initial value of the Discontinued property.</param>
    public static Product CreateProduct(global::System.Int32 productID, global::System.String productName, global::System.Boolean discontinued)
    {
        Product product = new Product();
        product.ProductID = productID;
        product.ProductName = productName;
        product.Discontinued = discontinued;
        return product;
    }

    #endregion
    #region Primitive Properties

    /// <summary>
    /// No Metadata Documentation available.
    /// </summary>
    [EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)]
    [DataMemberAttribute()]
    public global::System.Int32 ProductID
    {
        get
        {
            return _ProductID;
        }
        set
        {
            if (_ProductID != value)
            {
                OnProductIDChanging(value);
                ReportPropertyChanging("ProductID");
                _ProductID = StructuralObject.SetValidValue(value);
                ReportPropertyChanged("ProductID");
                OnProductIDChanged();
            }
        }
    }
    private global::System.Int32 _ProductID;
    partial void OnProductIDChanging(global::System.Int32 value);
    partial void OnProductIDChanged();

    /// <summary>
    /// No Metadata Documentation available.
    /// </summary>
    [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
    [DataMemberAttribute()]
    public global::System.String ProductName
    {
        get
        {
            return _ProductName;
        }
        set
        {
            OnProductNameChanging(value);
            ReportPropertyChanging("ProductName");
            _ProductName = StructuralObject.SetValidValue(value, false);
            ReportPropertyChanged("ProductName");
            OnProductNameChanged();
        }
    }
    private global::System.String _ProductName;
    partial void OnProductNameChanging(global::System.String value);
    partial void OnProductNameChanged();

我想添加数据注释到它的属性。我搜索intenet并根据这个话题:
使用DataAnnotations与实体框架

I want to add Data Annotation to it's property .I search intenet and according to this topic : Using DataAnnotations with Entity Framework

我以这种方式创建一个部分类:

I create a partial class this way:

[MetadataType(typeof(PersonMetaData))]
public partial class Product
{

}
public class PersonMetaData
{
    [Required(ErrorMessage = "nima", AllowEmptyStrings = false)]
    public global::System.String ProductName { set; get; }

    [Range(minimum: 10, maximum: 100, ErrorMessage = "NIIMMMAA")]
    public global::System.Int32 ProductID { set; get; }
}

但它不起作用。为了测试我写这段代码:

but it does not work. for test I write this code:

using (NorthwindEntities ef=new NorthwindEntities())
        {
            Product p = new Product();
            p.CategoryID = 0;
            p.Discontinued = false;
            p.ProductID = 1000;
            p.ProductName = string.Empty;
            p.QuantityPerUnit = "3";
            p.SupplierID = 3;
            p.UnitsInStock = 0;
            p.UnitsOnOrder = 3;

            var context = new ValidationContext(p, serviceProvider: null, items: null);
            var results = new List<System.ComponentModel.DataAnnotations.ValidationResult>();
            var isValid = Validator.TryValidateObject(p, context, results, true);
            if (!isValid)
            {
                foreach (var validationResult in results)
                {
                    Response.Write(validationResult.ErrorMessage);
                }
            }
        }

isValid 变量永远是'true'。我的错误在哪里?

but isValid variable always is 'true' . where is my mistake?

谢谢

推荐答案

更改

public class PersonMetaData
{
    [Required(ErrorMessage = "nima", AllowEmptyStrings = false)]
    public global::System.String ProductName { set; get; }

    [Range(minimum: 10, maximum: 100, ErrorMessage = "NIIMMMAA")]
    public global::System.Int32 ProductID { set; get; }
}

to

public class PersonMetaData
{
    [Required(ErrorMessage = "nima", AllowEmptyStrings = false)]
    public object ProductName { set; get; }

    [Range(minimum: 10, maximum: 100, ErrorMessage = "NIIMMMAA")]
    public object ProductID { set; get; }
}

这篇关于使用元数据与实体框架来验证使用数据注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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