zoukankan      html  css  js  c++  java
  • Linq to Oracle 使用教程(四)验证数据

    点击这里返回目录

     

    添加 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

    点击这里返回目录

     

     

  • 相关阅读:
    i++ ++i i=i+1 和i+=1
    cmd命令行 端口
    WAS 查看服务状态
    Linux 拷贝
    jar 压缩 解压 war包
    数据结构
    jar包生成exe可执行程序
    03-vant的一些事
    01-watch原理/computed原理
    05-问题集合
  • 原文地址:https://www.cnblogs.com/ansiboy/p/1894786.html
Copyright © 2011-2022 走看看