我正在使用Automapper将我的实体映射到DTO。在我的DTO中,我有一个Url属性,应根据请求和ID进行构建。映射完成后,我目前正在构建Url。 Automapper是否可以动态映射它?
以下是我的实体:
public class Food
{
public Food()
{
Measures = new List<Measure>();
}
public int Id { get; set; }
public string Description { get; set; }
public virtual ICollection<Measure> Measures { get; set; }
}
public class Measure
{
public int Id { get; set; }
public string Description { get; set; }
public virtual Food Food { get; set; }
}
以下是我的DTO的
public class FoodDto
{
public string Url { get; set; }
public int Id { get; set; }
public string Description { get; set; }
public IEnumerable<MeasureDto> Measures { get; set; }
}
public class MeasureDto
{
public string url { get; set; }
public int id { get; set; }
public string Description { get; set; }
}
映射完成后,我目前正在分配Url值,如下所示:
public IEnumerable<FoodDto> Get()
{
var foodWithMeasures = _repo.GetAllFoodsWithMeasures()
.OrderBy(f => f.Description)
.Take(25)
.ToList();
_urlHelper = new UrlHelper(this.Request);
var foodWithMeasuresDto = foodWithMeasures.Select(Mapper.Map<Food, FoodDto>);
var withMeasuresDto = foodWithMeasuresDto.ToList();
foreach (var food in withMeasuresDto)
{
string foodUrl = _urlHelper.Link("Food", new { id = food.Id });
food.Url = foodUrl;
foreach (var measures in food.Measures)
{
string measureUrl = _urlHelper.Link("Measure", new {foodid = food.Id, id = measures.id});
measures.Url = measureUrl;
}
}
return withMeasuresDto;
}
下面是我的MappingProfile类:
public MappingProfile()
{
Mapper.CreateMap<Food, FoodDto>();
Mapper.CreateMap<Measure, MeasureDto>();
}