在 .NET Framework 中进行数据注释的基本介绍






4.93/5 (29投票s)
在 .NET Framework 中进行数据注释的基本介绍
引言
在 .NET Framework 中,数据注释意味着通过添加属性标签来为数据添加额外的含义。 使用数据注释功能的优势在于,通过应用数据属性,我们可以在一个地方管理数据定义,而无需在多个地方重写相同的规则。
数据注释功能是在 .NET 3.5 中引入的,并且 System.ComponentModel.DataAnnotations
命名空间包含用作数据属性的类。
数据注释属性分为三类
- 验证属性:用于实施验证规则。
- 显示属性:用于指定如何将类/成员中的数据显示在 UI 中。
- 建模属性:用于指定类成员的预期用途以及类之间的关系。
在本文中,我将逐步介绍实现数据注释功能的基本步骤。 我使用 Visual Studio Express 2013 for Desktop 作为我的开发环境,目标框架为 .NET Framework 4.5。
首先,我们将创建我们的 Data
类,我们将其命名为 Employee
。 需求指出 Employee
类应该具有属性,例如 Name
、Age
、Email
和 Phone Number
,并满足以下条件。
Name
不能为空,并且应该至少包含 3 个字符,最多包含 100 个字符。Age
应该在 18 到 99 之间。Email
和Phone number
应该包含相应的数据类型验证。
注意:这只是一个旨在演示 .NET 数据注释功能的示例。 我将使用一些基本的数据注释属性,有关数据注释属性的更多详细信息,请参阅数据注释文档。
为了满足上述要求,我们需要在 UI 层中编写代码以适应/验证上述条件。 缺点是,如果我们在多个地方使用 Employee 类,我们需要重写验证逻辑,创建重复的代码,这不是一个好习惯。
这就是 .NET 数据注释功能的强大之处。 我们将数据注释属性添加到 Employee
类的属性中,.NET Framework 将为我们处理验证/显示。 我们可以将自定义错误消息作为数据注释属性的一部分添加。
步骤 1
创建一个空的解决方案,如下所示。 这将帮助我们稍后添加更多项目。
第二步
接下来,创建一个类库项目来将 Employee
类添加到解决方案中,如下所示。
添加一个名为 Employee.cs 的类,并添加对 System.ComponentModel.DataAnnotations
程序集的引用,以利用数据注释功能,如下所示
步骤 3
为了允许在 System.ComponentModel.DataAnnotations
中使用类型,将以下代码添加到 Employee.cs 中。
using System.ComponentModel.DataAnnotations;
步骤 4
将以下属性添加到 Employee
类,并带有相应的数据注释属性。
public class Employee
{
[Required (ErrorMessage="Employee {0} is required")]
[StringLength (100,MinimumLength=3,
ErrorMessage="Name Should be minimum 3 characters and a maximum of 100 characters")]
[DataType(DataType.Text)]
public string Name { get; set; }
[Range(18,99, ErrorMessage="Age should be between 18 and 99")]
public int Age { get; set; }
[DataType(DataType.PhoneNumber)]
[Phone]
Public string PhoneNumber { get; set; }
[DataType(DataType.EmailAddress)]
[EmailAddress]
Public string Email { get; set; }
}
步骤 5
使用控制台应用程序测试 Employee
类的数据验证。
创建一个新的控制台应用程序项目,并添加对 Employee 类库和 System.ComponentModel.DataAnnotations
程序集的引用。
我们的解决方案资源管理器如下所示
步骤 6
为了允许在 System.ComponentModel.DataAnnotations
和 Employee
类中使用类型,将以下代码添加到 Program.cs
using Model.Employee;
using System.ComponentModel.DataAnnotations;
namespace TestEmployeeValidation
{
class Program
{
static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("Employee class Validation");
Console.WriteLine("---------------------------\n");
Employee objEmployee = new Employee ();
objEmployee.Name = "sa";
objEmployee.Age = 12;
objEmployee.PhoneNumber = "1234as";
objEmployee.Email = "test@re";
ValidationContext context = new ValidationContext(objEmployee, null, null);
List<ValidationResult> results = new List<ValidationResult>();
bool valid = Validator.TryValidateObject(objEmployee, context, results, true);
if (!valid)
{
foreach (ValidationResult vr in results)
{
Console.ForegroundColor = ConsoleColor.Blue;
Console.Write("Member Name :{0}", vr.MemberNames.First());
Console.ForegroundColor = ConsoleColor.Red;
Console.Write(" :: {0}{1}", vr.ErrorMessage, Environment.NewLine);
}
}
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("\nPress any key to exit");
Console.ReadKey();
}
}
}
按 F5(或您在 Visual Studio 中配置的任何调试键)来验证 Employee
类。
现在,我们可以在控制台窗口中看到验证详细信息,如下所示,显示基于添加到 Employee
类的“数据注释”属性的验证错误。
在这里,使用数据注释属性的优势在于,现在如果要在 ASP.NET MVC 应用程序或 Windows Forms 应用程序中重用 Employee
类,我们仍然可以使用相同的验证,而无需编写任何额外的验证代码。
这只是关于如何使用 .NET 数据注释的初学者文章。 有关数据注释属性及其功能的更多详细信息,请参阅数据注释文档。