Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 743841
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 14, 20262026-05-14T08:54:35+00:00 2026-05-14T08:54:35+00:00

I’m trying to create a UniqueAttribute using the System.ComponentModel.DataAnnotations.ValidationAttribute I want this to be

  • 0

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; }

Edit:
Note that according to this: Why does C# forbid generic attribute types?
I cannot use a generic type with the attribute.

So my new approach here will be using Reflection/Expression trees to construct the Lambda expression tree on the fly.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-14T08:54:36+00:00Added an answer on May 14, 2026 at 8:54 am

    Well, after a bit of searching, I came across: http://forums.asp.net/t/1512348.aspx
    and I figured it out, although it involves a fair bit of code.

    Usage:

    [Required]
    [StringLength(10)]
    [Unique(typeof(ContactsManagerDataContext),typeof(Group),"name",ErrorMessage="Group already exists")]
    public string name { get; set; }
    

    The validator code:

    public class UniqueAttribute : ValidationAttribute
    {
        public Type DataContextType { get; private set; }
        public Type EntityType { get; private set; }
        public string PropertyName { get; private set; }
    
        public UniqueAttribute(Type dataContextType, Type entityType, string propertyName)
        {
            DataContextType = dataContextType;
            EntityType = entityType;
            PropertyName = propertyName;
        }
    
        public override bool IsValid(object value)
        {
            string str = (string) value;
            if (String.IsNullOrWhiteSpace(str))
                return true;
    
            // Cleanup the string
            str = str.Trim();
    
            // Construct the data context
            ConstructorInfo constructor = DataContextType.GetConstructor(new Type[0]);
            DataContext dataContext = (DataContext)constructor.Invoke(new object[0]);
    
            // Get the table
            ITable table = dataContext.GetTable(EntityType);
    
            // Get the property
            PropertyInfo propertyInfo = EntityType.GetProperty(PropertyName);
    
            // Expression: "entity"
            ParameterExpression parameter = Expression.Parameter(EntityType, "entity");
    
            // Expression: "entity.PropertyName"
            MemberExpression property = Expression.MakeMemberAccess(parameter, propertyInfo);
    
            // Expression: "value"
            object convertedValue = Convert.ChangeType(value, propertyInfo.PropertyType);
            ConstantExpression rhs = Expression.Constant(convertedValue);
    
            // Expression: "entity.PropertyName == value"
            BinaryExpression equal = Expression.Equal(property, rhs);
    
            // Expression: "entity => entity.PropertyName == value"
            LambdaExpression lambda = Expression.Lambda(equal, parameter);
    
            // Instantiate the count method with the right TSource (our entity type)
            MethodInfo countMethod = QueryableCountMethod.MakeGenericMethod(EntityType);
    
            // Execute Count() and say "you're valid if you have none matching"
            int count = (int)countMethod.Invoke(null, new object[] { table, lambda });
            return count == 0;
        }
    
        // Gets Queryable.Count<TSource>(IQueryable<TSource>, Expression<Func<TSource, bool>>)
        private static MethodInfo QueryableCountMethod = typeof(Queryable).GetMethods().First(m => m.Name == "Count" && m.GetParameters().Length == 2);
    }
    

    I don’t mind it being ugly since I will package it in a DLL and reuse it, much better than implementing multiple UniqueAttribute per table/field.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 539k
  • Answers 539k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer $("#gallery2 img").each( function() { var rNum = (Math.random()*4)-2; $(this).css( {… May 17, 2026 at 2:15 am
  • Editorial Team
    Editorial Team added an answer You're almost there: var foo = []; $('.bar').each(function(){ var self… May 17, 2026 at 2:15 am
  • Editorial Team
    Editorial Team added an answer Is this the expected results? Yes. This is the expected… May 17, 2026 at 2:15 am

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Related Questions

Basically, what I'm trying to create is a page of div tags, each has
I am trying to understand how to use SyndicationItem to display feed which is
I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
link Im having trouble converting the html entites into html characters, (&# 8217;) i
Does anyone know how can I replace this 2 symbol below from the string
this is what i have right now Drawing an RSS feed into the php,
That's pretty much it. I'm using Nokogiri to scrape a web page what has
Seemingly simple, but I cannot find anything relevant on the web. What is the
I have just tried to save a simple *.rtf file with some websites and

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.