使用元数据和实体框架来使用数据注释进行验证

发布于 2024-12-13 02:24:32 字数 4187 浏览 0 评论 0原文

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

[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 与实体框架结合使用

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

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

但它不起作用。为了测试,我编写了以下代码:

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' 。我的错误在哪里?

谢谢

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();

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

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

thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

墨小沫ゞ 2024-12-20 02:24:32

更改

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

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

Change

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; }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文