验证Entity Framework 4.0类的最佳方法是什么?

时间:2010-04-16 11:40:33

标签: wcf entity-framework wcf-data-services

我已经做了大量的搜索,但我还没有找到一种简单的方法来验证通过WCF数据服务传递的EntityFramework 4.0实体。基本上,我想在客户端做一些事情,如:

        Proxy.MyEntities entities = new Proxy.MyEntities(
            new Uri("http://localhost:2679/Service.svc"));

        Proxy.Vendor vendor = new Proxy.Vendor();

        vendor.Code = "ABC/XYZ";
        vendor.Status = "ACTIVE";

        // I'd like to do something like the following:
        vendor.Validate();

        entities.AddToVendors(vendor);

        entities.SaveChanges();

非常感谢这方面的任何帮助!

1 个答案:

答案 0 :(得分:0)

如果我是你,我会使用System.ComponentModel.DataAnnotations框架。

网上有很多例子。

您可以使用ValidationAttributes,如required,range等,并创建自己的属性来执行自定义验证。

请参阅以下如何验证实体。

Type objectType = entity.GetType();

Dictionary<string, string> errors = new Dictionary<string, string>();

foreach (PropertyInfo propertyInfo in objectType.GetProperties().Where(w => w.CanRead))
{
    object value = propertyInfo.GetValue(entity, null);

    foreach (ValidationAttribute validator in propertyInfo.GetCustomAttributes(typeof(ValidationAttribute), false))
    {
        if (!validator.IsValid(value))
        {
            errors.Add(propertyInfo.Name, validator.ErrorMessage);
        }
    }
}

如果您还需要其他任何内容,我希望这会有所帮助

方面

丹尼尔