Skip to content

Instantly share code, notes, and snippets.

@Sheeo
Created November 3, 2011 19:50
Show Gist options
  • Save Sheeo/1337590 to your computer and use it in GitHub Desktop.
Save Sheeo/1337590 to your computer and use it in GitHub Desktop.
Generic awesomeness in C#
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