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.
Pretty! This has been an incredibly wonderful post. Many thanks for providing these details.
{
{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