ASP.NET MVC 2验证的LINQ to SQL [英] ASP.NET MVC 2 validation LINQ to SQL

查看:139
本文介绍了ASP.NET MVC 2验证的LINQ to SQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我有一个包含我的LINQ to SQL类(一个dmbl文件)到DataModel对象。目前我使用的部分类来验证传入输入。例如:

Currently I have a DataModel object which contains my linq to sql classes(a dmbl file). Currently I use a partial class to validate the incoming input. For example

public partial class User : IEntity
{

    public NameValueCollection CheckModel()
    {
        return GetRuleViolations();
    }

    /// <summary>
    /// Method validates incoming data, by given rules in the if statement.
    /// </summary>
    /// <returns>NameValueCollection</returns>
    private NameValueCollection GetRuleViolations()
    {
        NameValueCollection errors = new NameValueCollection();
        if (string.IsNullOrEmpty(Username))
            errors.Add("Username", "A username is required");
        // and so on
        return errors;
    }

}

现在我想尝试做的是添加验证属性的字段。例如,我想尝试所需的属性添加到该领域,而不是用户名/用我目前拥有的验证addtion。我的问题是如何能够做到这一点,因为生成dmbl文件自动。或者,也许这是不可能的,我应该使用不同的方法?

Now what I want to try to do is add validation attributes to the fields. For example I want to try to add the required attribute to the field Username instead/in addtion of using the validation I currently have. My question is how can I achieve this because the dmbl file is auto generated. Or maybe it is not possible and should I use a different approach?

推荐答案

您应该阅读有关的元数据类。这是例子<一个href=\"http://blogs.renacimiento.com/eblanco/archive/2010/01/14/using-dataannotations-metadata-with-linq2sql-entities.aspx\"相对=nofollow>博客条目一下吧。

You should read about Metadata classes. This is example blog entry about it.

添加要求 atrribute到用户类将是这样的:

Adding Required atrribute to User class will be something like:

[MetadataType(typeof(UserMetadata))]
public partial class User
{
}

public class UserMetadata
{
    [Required]
    public string Username { get; set; }
}

这篇关于ASP.NET MVC 2验证的LINQ to SQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆