实体框架中的数据注释不起作用 [英] Data annotation in Entity Framework does not work

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

问题描述



我已经在实体框架的edmx文件后面的代码中使用了数据验证,如下所示:
[Range(1,5,ErrorMessage =输入1到5之间的值")]

Hi,

I have used a data validation in the code behind of edmx file of entity framework as:
[Range(1, 5, ErrorMessage = "Enter a value between 1 and 5")]

public global::System.Decimal UnitPrice
        {
            get
            {
                return _UnitPrice;
            }
            set
            {
                OnUnitPriceChanging(value);
                ReportPropertyChanging("UnitPrice");
                _UnitPrice = StructuralObject.SetValidValue(value);
                ReportPropertyChanged("UnitPrice");
                OnUnitPriceChanged();
            }
        }



当我在使用方应用程序上使用此实体时,它将不检查范围验证.



When I use this entity on consuming application then it does not check the range validation.

推荐答案

要实现此目的,您必须为中的每个实体类创建一个第二部分类EF并将其链接到具有替代属性的辅助类.

例如,您有一个生成的
To achieve this you have to create a 2nd partial class for each entity class in EF and link it to a auxiliary class with substitute properties.

for example you have a generated
class Product { public int UnitPrice{ get; set; } }


生成的类将始终标记为局部类.

现在您必须创建第二个部分类文件并添加


The generated class will always be marked as partial.

and now you have to create 2nd partial class file and add

[MetadataType(typeof(ProductMetadata))]
public partial class Product 
{
    // it's possible to add logic and non-mapped properties here
}


public class ProductMetadata
{
   [Range(1, 5, ErrorMessage = "Enter a value between 1 and 5")]
    public int UnitPrice { get; set; }   // note the 'object' type
}



会起作用的.
如果觉得有用,请对其评分.



It will work.
Rate it if you find it as useful.


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

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