【问题标题】:using Metadata with Entity Framework to validate using Data Annotation使用带有实体框架的元数据来验证使用数据注释
【发布时间】:2011-11-02 14:14:13
【问题描述】:

我有一个名为 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();

我想将数据注释添加到它的属性中。我搜索互联网并根据这个主题: Using DataAnnotations with Entity Framework

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

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

谢谢

【问题讨论】:

标签: c# entity-framework validation c#-4.0 data-annotations


【解决方案1】:

改变

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

【讨论】:

  • 它不起作用。我应该从第一个产品类中删除字段声明吗?我将我的项目上传到这个地址:4shared.com/file/kmmx_vRs/MetaData.html。这是一个表单测试应用程序。谢谢
  • 不,不要删除(编辑)生成的文件。您的设置看起来不错,我知道这适用于 MVC3。我不熟悉手动创建上下文等。请参阅此处的示例:msdn.microsoft.com/en-us/library/…
  • 作为诊断步骤,将[Range(5, 10)] public int MyProperty { get; set; } 添加到(现在为空)产品类。如果显示错误,则元数据链接中。
  • 然后通过谷歌搜索找到了这个答案:stackoverflow.com/questions/1871499/metadatatype-problem。我没有测试,但它看起来像你需要的修复。
  • 如果我使用原始数据类型,它可以工作。我认为将属性声明为object 没有必要
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-17
  • 1970-01-01
  • 1970-01-01
  • 2014-08-10
相关资源
最近更新 更多