How can I create a generaic ValidationAttribute in C#?

Posted by sabbour on Stack Overflow See other posts from Stack Overflow or by sabbour
Published on 2010-04-22T14:00:05Z Indexed on 2010/04/22 14:03 UTC
Read the original article Hit count: 702

I'm trying to create a UniqueAttribute using the System.ComponentModel.DataAnnotations.ValidationAttribute

I want this to be generic as in I could pass the Linq DataContext, the table name, the field and validate if the incoming value is unique or not.

Here is a non-compilable code fragment that I'm stuck at right now:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
using System.Data.Linq;
using System.ComponentModel;

namespace LinkDev.Innovation.Miscellaneous.Validation.Attributes
{
    public class UniqueAttribute : ValidationAttribute
    {
        public string Field { get; set; }

        public override bool IsValid(object value)
        {
            string str = (string)value;
            if (String.IsNullOrEmpty(str))
                return true;

            // this is where I'm stuck
            return (!Table.Where(entity => entity.Field.Equals(str)).Any());           
        }
    }
}

I should be using this in my model as follows:

[Required]
[StringLength(10)]
[Unique(new DataContext(),"Groups","name")]
public string name { get; set; }

© Stack Overflow or respective owner

Related posts about linq-to-sql

Related posts about dataannotations