代码改变世界

Linq to Oracle 使用教程(四)验证数据

  麦舒  阅读(1421)  评论(0编辑  收藏  举报

点击这里返回目录

 

添加 Validate Attribute 到属性

选取 Product 类中的 PropertyName 属性,在属性窗口中,选择 Attributes 项,然后点击旁边的按钮。在弹出的对话框中,双击左边 Attribute List 中的 RequiredAttribute 项,将其添加到右边。在属性窗口中,将 AllowEmptyString 设为 False ,点击 OK 按钮保存。

  

实现扩展方法

在设计器中,鼠标右键点击 Product 类,在弹出的菜单中,选择 ViewCode (或者按 F7 快捷键)。

导入命名空间

using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;

在 Prodcut 类中,添加下面的方法用于对实体类的属性进行验证。

 

复制代码
代码
partial void OnValidate(ALinq.ChangeAction action)
{
var propertyInfos
= this.GetType().GetProperties();
foreach (var propertyInfo in propertyInfos)
{
var customeAttributes
= propertyInfo.GetCustomAttributes(true)
.Where(o
=> o is ValidationAttribute)
.Cast
<ValidationAttribute>();

foreach (var attribute in customeAttributes)
{
attribute.Validate(propertyInfo.GetValue(
this, null), propertyInfo.Name);
}
}
}
复制代码

在 Program.cs 文件中,添加下面的代码:

复制代码
代码
static void Main(string[] args)
{
var dc
= new NorthwindDataContext()
{
Log
= Console.Out
};

var product
= new Product { Productname = "" };
dc.Products.InsertOnSubmit(product);
dc.SubmitChanges();
}
复制代码

按 Ctrl + F5 运行,从图中可以发现,抛出了一个异常,那是因为 ProductName 属性验证失败了。

关于更多验证方面的内容,请参考:

http://msdn.microsoft.com/en-us/library/cc488527.aspx

http://weblogs.asp.net/scottgu/archive/2007/07/11/linq-to-sql-part-4-updating-our-database.aspx

或者 Google : Linq to SQL validate

点击这里返回目录

 

 

编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· [AI/GPT/综述] AI Agent的设计模式综述
点击右上角即可分享
微信分享提示