为什么 UseValue 只执行一次? 我需要为每个请求调用TeamRepository。
我怎样才能做到这一点?
从 TeamEmployee 映射到 TeamEmployeeInput:
CreateMap<TeamEmployee, TeamEmployeeInput>()
.ForMember(x => x.Teams, x => x.UseValue(GetTeamEmployeeInputs()))
.ForMember(d => d.SelectedTeam, s => s.MapFrom(x => x.Team == null ? 0 : x.Team.Id));
private IEnumerable<TeamDropDownInput> GetTeamEmployeeInputs()
{
Team[] teams = CreateDependency<ITeamRepository>().GetAll();
return Mapper.Map<Team[], TeamDropDownInput[]>(teams);
}
域对象:
public class TeamEmployee : Entity
{
public virtual Employee Employee { get; set; }
public virtual Team Team { get; set; }
}
查看模型对象:
public class TeamEmployeeInput
{
public int? Id { get; set; }
public string EmployeeLastName { get; set; }
public string EmployeeEMail { get; set; }
public string EmployeeFirstName { get; set; }
public int SelectedTeam { get; set; }
public IList<TeamDropDownInput> Teams { get; set; }
}
public class TeamDropDownInput : IDropdownList
{
public int Id { get; set; }
public string Text { get; set; }
}
答案 0 :(得分:25)
尝试使用MapFrom
选项。它提供了一个代理,每次发生 map 时都会调用该代理。从快速的DateTime测试和我的命令窗口,这似乎有效。
类似的东西:
public class Foo {
public DateTime bar { get; set; }
}
public class Foo1
{
public DateTime bar1 { get; set; }
}
Mapper.CreateMap<Foo, Foo1>()
.ForMember(x => x.bar1, opt => opt.MapFrom(x => DateTime.Now)); // not using x, your function returns the value for bar1
我必须指出,这不是AutoMapper的设计方式。 AutoMapper应将属性从一个模型映射到另一个模型。因此,如果modelA
上的数据不存在,则您不应将数据映射到modelB
。
您的代码更改将是:
CreateMap<TeamEmployee, TeamEmployeeInput>()
.ForMember(x => x.Teams, x => x.MapFrom(x => GetTeamEmployeeInputs()))