我的项目使用EntityFramework 6.2,我不知道为什么在Razor视图中使用可空运算符?时会返回System.Data.Entity.DynamicProxies.MachineHW_06E2...9BE0?.CpuName
而不是字符串值
以这种方式不起作用:
@model MYApp.Models.MachineVM
...
<div class="flex-row">
<em>CPU: </em> @Model.Machine.MachineHW?.CpuName
</div>
代替使用此可读性较低的代码,它会起作用:
<em>CPU: </em>@if (Model.Machine.MachineHW != null){@Model.Machine.MachineHW.CpuName}
或
<em>CPU: </em>@(Model.Machine.MachineHW == null ? "" : Model.Machine.MachineHW.CpuName)
有效。
模型(Machine.cs):
public class Machine
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public virtual MachineHW MachineHW { get; set; }
}
模型(MachineHW.cs):
public class WorkloadMachineHW
{
[ForeignKey("Machine"), Key]
public int MachineId { get; set; }
public string CpuName { get; set; }
public virtual Machine Machine { get; set; }
}
ViewModel(MachineVM)
public class MachineVM
{
public Machine Machine { get; set; }
public bool someParam{ get; set; }
}
控制器
public ActionResult doMachine()
{
List<Machine> machinesList = db.Machine.Include(m => m.MachineHW).Where(some filter...).ToList();
MachineVM model = new MachineVM ();
model.Machine = machinesList.firstOrDefault();
model.someParam = true;
return View(model);
}
为什么可为空的运算符返回DynamicProxies而不是检查对象是否为空,然后显示其有效的值?