I am trying to develop some general purpose custom ValidationAttributes. The fact that one cannot create a generic subclass of an attribute is making me nuts.
Here is my code for the IsValid override in a ValidationAttribute to verify that the value of a property is unique:
public override bool IsValid(object value)
{
SomeDataContext context = SomeDataContext.GetNewDataContext();
Type tableType = typeof(Table<>).MakeGenericType(new Type[] { _EntityType });
var table = Activator.CreateInstance(tableType);
//ITable table = context.GetTable(_EntityType);
var codeProp = (from member in context.Mapping.GetMetaType(_EntityType).DataMembers
where member.Name == _PropertyName
select member.Member).Single();
ParameterExpression param = Expression.Parameter(_EntityType, "x");
MemberExpression memberExp = Expression.Property(param, (PropertyInfo)codeProp);
Expression body = Expression.Equal(memberExp, Expression.Constant(value, typeof(char)));
//var predicate = Expression.Lambda<Func<TEntityType, bool>>(body, param);
Type lambdaType = typeof(Func<,>).MakeGenericType(_EntityType, typeof(bool));
var predicate = Expression.Lambda(lambdaType, body, param);
object code = table.FirstOrDefault(predicate);
if (code != null)
{
return false;
}
return true;
}
This line:
object code = table.FirstOrDefault(predicate);
errors out:
'object' does not contain a definition for 'FirstOrDefault' and no extension ......etc.
How do I define, cast or otherwise get the compiler to recognize "table" as something that exposes a .FirstOrDefault method?
Thanks