AutoMapper目前没有拉下IpAddress
对象中的Server
对象。最终目标是在我的编辑视图中使用当前IP地址填充我的输入。但是,当我在Controller中放置一个断点时,IpAddress
属性为null,因此我无法从中获取实际地址。我知道我在使用AutoMapper做错了什么,但还没找到具体的教程。提前谢谢!
ServersController.cs
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var server = Mapper.Map<ServerViewModel>(await _context.Servers.SingleOrDefaultAsync(m => m.Id == id));
if (server == null)
{
return NotFound();
}
return View(server);
}
ServerViewModel.cs
public class ServerViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public OperatingSystem OS { get; set; }
public MachineType MachineType { get; set; }
public string AdminUserName { get; set; }
public string AdminPassword { get; set; }
public string EsxHost { get; set; }
public int IpAddressId { get; set; }
public IpAddress IpAddress { get; set; }
public List<SelectListItem> GetOperatingSystems()
{
List<SelectListItem> operatingSystems = new List<SelectListItem>();
Array values = Enum.GetValues(typeof(OperatingSystem));
operatingSystems.Add(new SelectListItem
{
Text = "Select",
Value = ""
});
foreach(OperatingSystem val in values)
{
operatingSystems.Add(new SelectListItem
{
Text = val.ToString(),
Value = val.ToString()
});
}
return operatingSystems;
}
public List<SelectListItem> GetMachineTypes()
{
List<SelectListItem> machineTypes = new List<SelectListItem>();
Array values = Enum.GetValues(typeof(MachineType));
machineTypes.Add(new SelectListItem
{
Text = "Select",
Value = ""
});
foreach (MachineType val in values)
{
machineTypes.Add(new SelectListItem
{
Text = val.ToString(),
Value = val.ToString()
});
}
return machineTypes;
}
}
Server.cs
public class Server
{
[Key]
[Required]
public int Id { get; set; }
public string Name { get; set; }
public OperatingSystem OS { get; set; }
[Display(Name = "Machine Type")]
public MachineType MachineType { get; set; }
[Display(Name = "Admin User Name")]
public string AdminUserName { get; set; }
[Display(Name = "Admin Password")]
public string AdminPassword { get; set; }
[Display(Name = "ESX Host")]
public string EsxHost { get; set; }
public int IpAddressId { get; set; }
[ForeignKey("IpAddressId")]
public IpAddress IpAddress { get; set; }
}
Startup.cs
Mapper.Initialize(config =>
{
config.CreateMap<IpAddressViewModel, IpAddress>().ReverseMap();
config.CreateMap<ServerViewModel, Server>().ReverseMap();
});
编辑:经过一些阅读,我发现我可以在查询中添加.Include()
子句以引入IpAddress
对象。我的新ServersController.cs
代码如下。但是,我仍然有点困惑。这不是Automapper自动处理的事情吗?我错过了Automapper的全部内容吗?
NEW ServersController.cs
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var server = Mapper.Map<ServerViewModel>(await _context.Servers.Include(s => s.IpAddress).SingleOrDefaultAsync(m => m.Id == id));
if (server == null)
{
return NotFound();
}
return View(server);
}
答案 0 :(得分:0)