如何为我的实体创建自定义验证

发布于 2024-10-10 11:38:53 字数 166 浏览 0 评论 0原文

我想知道是否可以为我的用户实体创建自定义验证。

我想验证用户名是否唯一。 如果用户已经存在,我不想保存它并显示警告。

我读过有关数据注释继承的内容,但我不确定我在做什么。

请帮忙。

谢谢。

实体框架 4
ASP.NET MVC 2

I would like to know if this is possible to create a custom validation for my User Entity.

I Want to verify if the username is unique.
If the user Already exist, I don't want to save it and show a warning.

I Read about Data Annotation inherits but I'm not sure of what I'm doing.

Please help.

Thanks.

Entity-Framework 4
Asp.net MVC 2

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

亣腦蒛氧 2024-10-17 11:38:53

是的,这是可能的,您可以创建自己的自定义属性类并验证实体。与此代码类似的内容,

    [AttributeUsage(AttributeTargets.Class)]
    public class DuplicateUserAttribute : ValidationAttribute
    {
    private const string _defaultErrorMessage = "user '{0}' Already exist";

    public DuplicateUserAttribute ()
        : base(_defaultErrorMessage)
    {
    }

    public override string FormatErrorMessage(string name)
    {
        return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString);

    }

    public override bool IsValid(object value)
    {
        UserEntity NewUser = value as UserEntity;
        //Write here logic to validate the user is already exist in database like
        context.UserList.Where(u=>u.Name ==NewUser .UserName)
        return ;
    }
}

[DuplicateUser]
Class User
{
 …
}

还有更多关于 CustomeAttribute

Yes it is possible, you can create your own Custom Attribute class and validate the entity. Something similar to this code,

    [AttributeUsage(AttributeTargets.Class)]
    public class DuplicateUserAttribute : ValidationAttribute
    {
    private const string _defaultErrorMessage = "user '{0}' Already exist";

    public DuplicateUserAttribute ()
        : base(_defaultErrorMessage)
    {
    }

    public override string FormatErrorMessage(string name)
    {
        return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString);

    }

    public override bool IsValid(object value)
    {
        UserEntity NewUser = value as UserEntity;
        //Write here logic to validate the user is already exist in database like
        context.UserList.Where(u=>u.Name ==NewUser .UserName)
        return ;
    }
}

[DuplicateUser]
Class User
{
 …
}

Also more on CustomeAttribute

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文