Reputation: 755321
Based on a number of posts here on SO, I am trying to create an extension method for AutoMapper so that for all my EF 4.0 business objects, all the EF-relevant properties of types EntityReference<T>
and EntityCollection<T>
are excluded from a mapping.
I have come up with this code:
public static class IgnoreEfPropertiesExtensions {
public static IMappingExpression<TSource, TDestination> IgnoreEfProperties<TSource, TDestination>(
this IMappingExpression<TSource, TDestination> expression) {
var sourceType = typeof (TSource);
foreach (var property in sourceType.GetProperties()) {
// exclude all "EntityReference" and "EntityReference<T>" properties
if (property.PropertyType == typeof(EntityReference) ||
property.PropertyType.IsSubclassOf(typeof(EntityReference)))
{
expression.ForMember(property.Name, opt => opt.Ignore());
}
// exclude all "EntityCollection<T>" properties
if (property.PropertyType == typeof(EntityCollection<>))
{
expression.ForMember(property.Name, opt => opt.Ignore());
}
}
return expression;
}
}
but somehow, while it works just fine the EntityReference<T>
properties, for the collection, this doesn't do what it should do - AutoMapper still tries to map the EntityCollection<MySubEntity>
and crashes on attempting this....
How can I properly catch all the EntityCollection<T>
properties? I don't really care about what the subtype <T>
is - I don't want to specify that, all properties of type EntityCollection<T>
(regardless of what the collection contains) need to be excluded from the mapping.
Any ideas?
Upvotes: 1
Views: 313