【发布时间】:2021-04-06 19:34:09
【问题描述】:
我正在开发一个 .NET 5 API。
我必须用一个序列化 UnitDto 类的 Json 回复 get 调用,并在其中包含所有 InstDto 类的列表,但我需要一个驻留的属性UnitInst 对象(多对多表)
我的课:
public class Unit
{
public long Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public virtual ICollection<UnitInst> UnitInsts { get; set; }
}
public class Inst
{
public long Id { get; set; }
public string Name { get; set; }
public virtual ICollection<UnitInst> UnitInsts { get; set; }
}
public class UnitInst
{
public long Id { get; set; }
public long UnitId { get; set; }
public virtual Unit Unit { get; set; }
public long InstId { get; set; }
public virtual Inst Inst { get; set; }
public string IPv4 { get; set; } // the property that is important
}
我的 dto 的
public class UnitDto
{
public long Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public IEnumerable<InstDTO> Insts { get; set; }
}
public class InstDTO
{
public long Id { get; set; }
public string Name { get; set; }
public string IPv4 { get; set; } // I need serialize this property in my response json
}
我以这种方式映射,没关系,但我无法从 UnitInst 类(多对多表)中检索 IPv4 属性
CreateMap<Unit, UnitDto>()
.ForMember(dto => dto.Insts, opt => opt.MapFrom(x => x.UnitInsts.Select(y => y.Inst).ToList()))
.PreserveReferences();
我该如何解决?
【问题讨论】:
-
这里缺少一些信息。有
Inst和Instrument,还有UnitInst和UnitInstrument。这两对是一回事吗? -
@Dialectus 对不起,我的错误我已经更新了问题,这里只存在 Inst 类
标签: c# asp.net-core entity-framework-core automapper asp.net5