zoukankan      html  css  js  c++  java
  • ALinq 使用教程(四)验证实体类

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

  • 相关阅读:
    驱动程序细节和权衡
    交互
    查找UI元素
    Selenium-Webdriver API命令和操作-Get & Wait
    Selenium的webdriver
    openssl生成ssl证书
    tony_nginx_02_URL重写
    CPA
    消息队列产品比较
    元数据交换绑定的秘密
  • 原文地址:https://www.cnblogs.com/ansiboy/p/2037404.html
Copyright © 2011-2022 走看看