Custom Attribute to Validate Duplicate Entity

This post is for Duplicate Entity check using C# Attributes,(Based on the question which I recently answered)

If you want to check whether any entity present in database or not, so this can be achieved using Custom Attribute which is mentioned below,

I put this as a Class level attribute but you can extend it and make it for Property levels also.

Attribute Class code as goes..
[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 ;
}
}

Now you can use simply,
[DuplicateUser]
Class User
{

}

You need give reference of System.ComponentModel.DataAnnotations.dll.
In System.ComponentModel.DataAnnotations.dll you can find many predefined attributes also like, RequiredAttribute, DataTypeAttribute.

About these ads
This entry was posted in Uncategorized and tagged , , , , , , , , , , . Bookmark the permalink.

2 Responses to Custom Attribute to Validate Duplicate Entity

  1. Pretty! This has been an incredibly wonderful post. Many thanks for providing these details.

  2. {
    {I have|I’ve} been {surfing|browsing} online more than {three|3|2|4} hours today, yet I never found any interesting article like yours. {It’s|It is}
    pretty worth enough for me. {In my opinion|Personally|In my view},
    if all {webmasters|site owners|websi

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s