使用UseValue将自定义值传递给Automapper

时间:2018-11-05 16:34:40

标签: c# asp.net-core automapper

我正在控制器中使用Automapper,但是第一次调用后并没有刷新数据。

public class Somethings
{
    public int Id {get; set;}
    public string Info1 {get; set;}
    public string Info2  {get; set;}
}

public class Details
{
    public int Id {get; set;}
    public string Detail1 {get; set;}
    public string Details2  {get; set;}
    public DateTime LogDate {get; set;}
}   

public class SomethingDetails : Somethings
{
    public string SomethingSpecific {get; set;}
}   

public async Task<IActionResult> Details(int? id)
{
    var somethings = await _context.Somethings
        .SingleOrDefaultAsync(m => m.Id == id);

    var details = await _context.Details.OrderByDescending(o => o.LogDate).FirstOrDefaultAsync(m => m.IdSomething == id);

    var somethingSpecific = details.Detail1;

    SomethingDetails somethingDetails = _mapper.Map<Somethings, SomethingDetails>(somethings, opt => opt.ConfigureMap().ForMember(d => d.SomethingSpecific, a => a.UseValue(somethingSpecific)));

    return View(somethingDetails);
}

somethingDetails.SomethingSpecific值在第一次调用Details后不会更改。我看到一对夫妇从Automapper的早期版本中解决了这个问题,但我认为UseValue仅用于此目的。我错了吗?

1 个答案:

答案 0 :(得分:0)

我根据您的代码制作了一个演示,它起作用了。 尝试在以下代码中将“ IdSomething”更改为“ Id”

var details = await _context.Details.OrderByDescending(o => o.LogDate).FirstOrDefaultAsync(m => m.IdSomething == id);