我正在使用virtual
关键字为我的一些属性进行EF延迟加载。将源映射到目标时,我的模型中标记为virtual
的所有属性应该从AutoMapper中忽略。如何忽略所有标记为虚拟的属性
是否有一种自动方式可以实现这一点,或者我应该手动忽略每个成员?
我正在使用virtual
关键字为我的一些属性进行EF延迟加载。将源映射到目标时,我的模型中标记为virtual
的所有属性应该从AutoMapper中忽略。如何忽略所有标记为虚拟的属性
是否有一种自动方式可以实现这一点,或者我应该手动忽略每个成员?
您可以创建一个映射扩展并使用它:
namespace MywebProject.Extensions.Mapping
{
public static class IgnoreVirtualExtensions
{
public static IMappingExpression<TSource, TDestination>
IgnoreAllVirtual<TSource, TDestination>(
this IMappingExpression<TSource, TDestination> expression)
{
var desType = typeof(TDestination);
foreach (var property in desType.GetProperties().Where(p =>
p.GetGetMethod().IsVirtual))
{
expression.ForMember(property.Name, opt => opt.Ignore());
}
return expression;
}
}
}
用法:
Mapper.CreateMap<Source,Destination>().IgnoreAllVirtual();
inquisitive
的回答能正常工作,但它可以增强现实生活中的使用,当从数据模型执行一些映射到服务模型时,应该忽略来自源类型的虚拟成员。另外,如果类型实现了某些接口,那些属性将显示为虚拟的,因此必须添加!IsFinal
条件才能删除这些虚假肯定的虚拟属性。
public static class AutoMapperExtensions
{
public static IMappingExpression<TSource, TDestination> IgnoreAllDestinationVirtual<TSource, TDestination>(this IMappingExpression<TSource, TDestination> expression)
{
var desType = typeof(TDestination);
foreach (var property in desType.GetProperties().Where(p => p.GetGetMethod().IsVirtual && !p.GetGetMethod().IsFinal))
{
expression.ForMember(property.Name, opt => opt.Ignore());
}
return expression;
}
public static IMappingExpression<TSource, TDestination> IgnoreAllSourceVirtual<TSource, TDestination>(this IMappingExpression<TSource, TDestination> expression)
{
var srcType = typeof(TSource);
foreach (var property in srcType.GetProperties().Where(p => p.GetGetMethod().IsVirtual && !p.GetGetMethod().IsFinal))
{
expression.ForSourceMember(property.Name, opt => opt.Ignore());
}
return expression;
}
}
您不能在automapper开箱即用,但可以使用此规则在代码中创建地图。 –
好奇,你为什么要忽略这些?如果你想忽略它们,为什么它们会成为你的目标类型? –
这些是EF Code First Models中其他实体的导航属性。创建新条目时,我需要将我的视图模型与表单中的数据映射到域模型中的属性(Ef Code First模型)。通常不映射属性不会导致任何错误或异常,但我在单元测试中使用AutoMapper的Mapper.AssertConfigurationIsValid(),如果我没有映射目标模型的所有属性,断言将引发异常 –