我发现ProjectTo可以为导航属性生成不同的对象。我会举例说明。
我的模特:
public class Element
{
public Guid Id { get; set; }
public string Name { get; set;}
}
public class CircuitElement
{
public Guid Id { get; set; }
public Guid ElementId { get; set; }
public Guid CircuitId { get; set; }
public Element Element { get; set;}
}
当我仅使用EF.Core请求时,我在每个CircuitElement的导航属性中都得到了完全相同的Element对象:
List<CircuitElement> circuitElements = UnitOfWork.GetRepository<CircuitElement>()
.GetQuery(csc => csc.CircuitId == circuitId)
.Include(x => x.Element)
.ToList();
var elements = circuitElements.Select(x => x.Element).Where(x => x.Id == GuidConst.AxElement).ToList();
var comp1 = ReferenceEquals(elements[0], elements[1]); //returns true
var comp2 = ReferenceEquals(elements[0], elements[2]); //returns true
然后我要添加DTO,MappingProfile和ProjectTo:
public class ElementDto
{
public Guid Id { get; set; }
public string Name { get; set;}
}
public class CircuitElementDto
{
public Guid Id { get; set; }
public Guid ElementId { get; set; }
public Guid CircuitId { get; set; }
public ElementDto Element { get; set;}
}
public class MappingProfile : Profile
{
public MappingProfile()
{
CreateMap<Element, ElementDto>(MemberList.None);
CreateMap<ElementDto, Element>(MemberList.None);
CreateMap<CircuitElement, CircuitElementDto>(MemberList.None);
CreateMap<CircuitElementDto, CircuitElement>(MemberList.None);
}
}
List<CircuitElementDto> circuitElements = UnitOfWork.GetRepository<CircuitElement>()
.GetQuery(csc => csc.CircuitId == circuitId)
.Include(x => x.Element)
.ProjectTo<CircuitElementDto>(Mapper.ConfigurationProvider)
.ToList();
var elements2 = circuitElements.Select(x => x.Element).Where(x => x.Id == GuidConst.AxElement).ToList();
var comp3 = ReferenceEquals(elements[0], elements[1]); //returns FALSE
var comp4 = ReferenceEquals(elements[0], elements[2]); //returns FALSE
如您所见,这些元素是不同的对象。 是否可以配置Automapper,所以它将为所有这些导航生成一个对象,而不是3个?还是在ToList之后有合并它们的技术?