如何忽略嵌套的嵌套对象与ProjectTo在Automapper?



是否可以在惰性加载时忽略嵌套的嵌套对象?

public class Parent
{
public List<Child> Children;
}
public class Child
{
public List<SomeObject> SomeObjects;
}

当定义Parent时,需要忽略Children中的Someobject字段,但是当只定义Child时,不需要忽略它.

如果不添加没有字段的子类的副本,这是可能的吗?不仅需要删除对象,还需要在SQL查询期间忽略它。

//SomeObjects inside Child must be empty
var parent = _mapper.ProjectTo<ParentDTO>(_dbContext.Parent.Where(c => c.Id == id)).FirstOrDefault();
//not ignored SomeObjects inside Child
var child = _mapper.ProjectTo<ChildDTO>(_dbContext.Children.Where(c => c.Id == id)).FirstOrDefault();

感谢您的宝贵时间

解决方法如下

CreateMap<Child, ChildDTO>
.ForMember(_ => _.SomeObjects, opt => opt.ExplicitExpansion())
.ForAllMembers(_ => _.UseDestinationValue());
//calls
var parent = _mapper.ProjectTo<ParentDTO>(_dbContext.Parents.Where(c => c.Id == id)).FirstOrDefault();
var client = _mapper.ProjectTo<ChildDTO>(
_dbContext.Children.Where(c => c.Id == id),
null,                    
c => c.SomeObjects  //include SomeObjects
).FirstOrDefault();

相关内容

  • 没有找到相关文章

最新更新