48550

Trying to get generic when generic is not available

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

Answer1:

This will get you to a type that System.Linq.Enumerable can use:

IEnumerable<object> tableGeneric = ((IEnumerable)table).OfType<object>();

Three concerns:

<ol> <li>Don't use var so much - you'll lose track of your types.</li> <li>I'm unsure about using your predicate in a FirstOrDefault call - I don't see how the compiler can type check it. http://msdn.microsoft.com/en-us/library/bb299425.aspx</li> <li>If you get the predicate working, .Any() might be a better choice than .FirstOrDefault()</li> </ol>

Answer2:

How do I define, cast or otherwise get the compiler to recognize "table" as something that exposes a .FirstOrDefault method?

By using an explicit cast to IEnumerable<> of something. Since you don't know the “something” in your case, you effectively cannot use FirstOrDefault. Simply implement the logic yourself:

var enumerator = ((IEnumerable)table).GetEnumerator(); object code = enumerator.MoveNext() ? enumerator.Value : null;

Recommend

  • How to implement outer join expression tree?
  • Spring Integration, delete file in outbound channel adapter
  • Launch AutoCAD 2015 from .Net process
  • vb.net running a exe in memory
  • Using sfFilter to update DB with Doctrine
  • How to Set Custom DataGridView Headers (with spaces) using LINQ?
  • Relative Path to load a library?
  • Having trouble on rendering data to angular
  • “ java.lang.IllegalStateException: The driver is not executable” error is coming when TestNG test ca
  • when reversing a Scan in HBase, which is the startKey and which is the stopKey?
  • How do I call DotNetFactory from VBScript in a stand-alone .vbs file?
  • Spring integration warning Referenced bean 'org.springframework.scheduling.support.PeriodicTrig
  • SQL Need a query that returns every field that contains a specified letter
  • Dynamically generated lookup key for IQueryable
  • C++ friend class std::vector
  • SetWindowsHookEx does not react on media keys
  • Implicit joins and Where in Doctrine - how?
  • Low TTL with Leveled Compaction, should I reduce gc_grace_seconds to improve read performance withou
  • Scala multiline string placeholder
  • close() was never explicitly called on database
  • Eliminate partial duplicate rows from result set
  • How to assign byte[] as a pointer in C#
  • Unable to get column index with table.getColumn method using custom table Model
  • How can I extract results of aggregate queries in slick?
  • How to test if a URL from an Eclipse bundle is a directory?
  • Word Open XML Mail Merge
  • Replace value with Factor in r data.table
  • Database structure design with variable amounts of fields
  • How to delay loading a property with linq to sql external mapping?
  • Jenkins: How To Build multiple projects from a TFS repository?
  • Submit form in a displaytag pagination
  • output of program is not same as passed argument
  • Delete MySQLi record without showing the id in the URL
  • Unanticipated behavior
  • Comma separated Values
  • Unit Testing MVC Web Application in Visual Studio and Problem with QTAgent
  • Observable and ngFor in Angular 2
  • UserPrincipal.Current returns apppool on IIS
  • Conditional In-Line CSS for IE and Others?
  • java string with new operator and a literal