本文介绍了最佳实践实体验证在ASP.NET MVC& ADO.NET实体框架的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ASP.NET MVC&项目中的ADO.NET实体框架。我想通过部分类向我的实体添加验证逻辑。它的工作原理类似于所示,该应用程序正在使用LINQ2SQL。主要的区别是,我必须使用OnPropertyChanging事件,而不是像LINQ2SQL中的OnValidating。



这样做有一些问题:
- OnPropertyChanging事件不是调用验证逻辑的最佳点,因为即使创建一个调用默认构造函数,它也总是触发。这真的可以导致严重的问题(不仅是性能问题)。
- 与MVC框架一起使用EntityState.Detached(我找不到任何其他方式)来确定一个实体是否需要验证是有问题的。因为在视图中显示实体时,实体失去了实体的身份(因为POST事件创建了一个新的实体对象而不是返回原始对象)。



我的问题是:有没有更好的方式向ADO.NET实体添加验证?我找不到任何使用向ADO.NET实体添加验证的实用方法的教程。

解决方案

个人而言,在对象本身中进行验证。我使用库来处理我的实体验证。



xVal鼓励您用描述各种验证规则的属性来注释实体类(或实际上是元数据伴随类)。这些验证属性是System.ComponentModel.DataAnnotations中.NET的默认属性。



然后,您可以在业务层中手动运行对对对象的验证。这通过使用运行System.ComponentModel.DataAnnotations验证逻辑的方法来完成。我写了一个如下所示:

  ///< summary> 
///通过使用反射来获取传入的对象的验证错误,以检索其属性或属性上的
///< see cref =ValidationAttribute/>对象的
///元数据类(由对象的类放置的< see cref =MetadataTypeAttribute/>指定)
///< / summary>
///< param name =instance>要验证的对象< / param>
///< returns>任何验证错误< / returns>
///< remarks>
///借阅(并清理)
/// http://goneale.com/2009/03/04/using-metadatatype-attribute-with-aspnet-mvc-xval-validation -framework /
///< / remarks>
public static IEnumerable< ErrorInfo>验证(对象实例)
{
//尝试从对象获取MetadataType属性
MetadataTypeAttribute metadataAttrib = instance.GetType()。GetCustomAttributes(typeof(MetadataTypeAttribute),true).OfType& MetadataTypeAttribute>()FirstOrDefault();

//如果MetadataType属性存在,获取元数据类
//否则只需使用对象的类
键入buddyClassOrModelClass = metadataAttrib!= null? metadataAttrib.MetadataClassType:instance.GetType();

IEnumerable< PropertyDescriptor> buddyClassProperties = TypeDescriptor.GetProperties(buddyClassOrModelClass).Cast< PropertyDescriptor>();
IEnumerable< PropertyDescriptor> modelClassProperties = TypeDescriptor.GetProperties(instance.GetType())。Cast< PropertyDescriptor>();

//此查询与模型类中的每个属性与好友类匹配
//获取所有无效验证属性的列表,并返回
//验证错误列表
从buddyProp返回buddyClassProperties
在buddyProp.Name中的modelClassProperties中连接modelProp等于modelProp.Name
来自buddyProp.Attributes.OfType&ValidationAttribute。()
其中!属性的属性。 IsValid(modelProp.GetValue(instance))
选择新的ErrorInfo(buddyProp.Name,attribute.FormatErrorMessage(String.Empty),instance);
}

xVal提供了一个整洁的异常类型,可以抛出封装验证错误并允许您轻松地将它们添加到Controller中的ModelState中。



xVal还将通过提供HtmlHelper方法来利用jQuery.Validate自动生成客户端JavaScript表单验证码。



查看,了解如何作品。我发现它是非常好的验证方式,这不是一个全部的烦恼。它适合于ASP.NET MVC的做事方式。


i am using ASP.NET MVC & ADO.NET Entity Framework in a project. I want to add validation logic to my entities via partial classes. It works similar like shown in the NerdDinner.com ASP.NET MVC Application which is using LINQ2SQL. The main difference is, that i have to use the"OnPropertyChanging" event instead the "OnValidating" like in LINQ2SQL.

There are some problems when doing it that way:- The "OnPropertyChanging" event is not the optimal point of calling validation logic, because it always triggers, even on creating a calling the default constructor. This really can cause serious problems (not only performance problems).- Together with the MVC framework there are problems when using the "EntityState.Detached" (i couldn't find any other way) to determine if a entity needs to be validated or not. Because a entity loses its entity sate during it gets displayed in the view (because on POST-event a new entity object is created instead of returning the original one).

My question is: Is there a better way of adding validation to ADO.NET Entities? I couldn't find any tutorials using a practical way of adding validation to ADO.NET Entities.

解决方案

Personally, I don't put validation in the objects themselves. I use the xVal library to handle my entity validation.

xVal encourages you to annotate your entity classes (or, actually, metadata companion classes) with attributes that describe the various validation rules. These validation attributes are the default ones that come with .NET in System.ComponentModel.DataAnnotations.

You then run validation against your objects manually in your business layer. This is done by using a method that runs the System.ComponentModel.DataAnnotations validation logic. I wrote one that looks like this:

/// <summary>
/// Gets the validation errors for the passed in object by using reflection to retrieve the
/// <see cref="ValidationAttribute"/>s placed on its properties or on the properties of the object's
/// metadata class (as specified by a <see cref="MetadataTypeAttribute"/> placed on the object's class)
/// </summary>
/// <param name="instance">The object to validate</param>
/// <returns>Any validation errors</returns>
/// <remarks>
/// Borrowed (and cleaned up) from
/// http://goneale.com/2009/03/04/using-metadatatype-attribute-with-aspnet-mvc-xval-validation-framework/
/// </remarks>
public static IEnumerable<ErrorInfo> Validate(object instance)
{
    //Try to get the MetadataType attribute from the object
    MetadataTypeAttribute metadataAttrib = instance.GetType().GetCustomAttributes(typeof(MetadataTypeAttribute), true).OfType<MetadataTypeAttribute>().FirstOrDefault();

    //If the MetadataType attribute existed, get the metadata class
    //else just use the class of the object
    Type buddyClassOrModelClass = metadataAttrib != null ? metadataAttrib.MetadataClassType : instance.GetType();

    IEnumerable<PropertyDescriptor> buddyClassProperties = TypeDescriptor.GetProperties(buddyClassOrModelClass).Cast<PropertyDescriptor>();
    IEnumerable<PropertyDescriptor> modelClassProperties = TypeDescriptor.GetProperties(instance.GetType()).Cast<PropertyDescriptor>();

    //This query matches each property on the model class against the buddy class
    //gets a list of all invalid validation attributes and returns a list of
    //validation errors
    return from buddyProp in buddyClassProperties
           join modelProp in modelClassProperties on buddyProp.Name equals modelProp.Name
           from attribute in buddyProp.Attributes.OfType<ValidationAttribute>()
           where !attribute.IsValid(modelProp.GetValue(instance))
           select new ErrorInfo(buddyProp.Name, attribute.FormatErrorMessage(String.Empty), instance);
}

xVal provides a neat exception type you can throw that encapsulates validation errors and allows you to easily add them to the ModelState in your Controller.

xVal also will autogenerate client-side JavaScript form validation code for you by leveraging jQuery.Validate by providing an HtmlHelper method.

Check out http://blog.codeville.net/2009/01/10/xval-a-validation-framework-for-aspnet-mvc/ for a walkthrough on how it works. I've found it to be very nice way of doing validation that's not a total chore. It fits right in in the ASP.NET MVC way of doing things.

这篇关于最佳实践实体验证在ASP.NET MVC&amp; ADO.NET实体框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 21:56