Created
November 3, 2011 19:50
-
-
Save Sheeo/1337590 to your computer and use it in GitHub Desktop.
Generic awesomeness in C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public void Add<TEntity>(TEntity t) where TEntity : class | |
{ | |
var properties = (from p in GetType().GetProperties() | |
select p.GetGetMethod(true)); | |
var genericProperties = (from property in GetType().GetProperties() | |
let returntype = property.GetGetMethod(true).ReturnType | |
where returntype.IsGenericType | |
where returntype.GetGenericArguments().Length == 1 | |
let argumenttype = returntype.GetGenericArguments().First() | |
where argumenttype == typeof (TEntity) | |
select property).ToList(); | |
if (genericProperties.Count() == 0) | |
throw new RepositoryException("Zero DbSets found matching type: " + typeof(TEntity)); | |
if(genericProperties.Count() > 1) | |
throw new RepositoryException("More than one DbSet of type: " + typeof(TEntity)); | |
return genericProperties.First().GetGetMethod(true).Invoke(this, null); | |
var dbSetProperty = genericProperties.First(); | |
try | |
{ | |
var dbSet = dbSetProperty.GetGetMethod(true).Invoke(this, null); | |
dbSet.GetType().InvokeMember("Add", BindingFlags.Public, null, dbSet, new object[] {t}); | |
} | |
catch (TargetInvocationException e) | |
{ | |
throw e.InnerException; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment