C# 自动映射,映射多对多表上的属性
我正在开发一个.NET5API 我必须用一个Json来响应get调用,该Json序列化了UnitDto类,并在其中列出了所有InstDto类,但我需要一个驻留在UnitInst对象(表多对多)上的属性 我的班级:C# 自动映射,映射多对多表上的属性,c#,asp.net-core,entity-framework-core,automapper,asp.net5,C#,Asp.net Core,Entity Framework Core,Automapper,Asp.net5,我正在开发一个.NET5API 我必须用一个Json来响应get调用,该Json序列化了UnitDto类,并在其中列出了所有InstDto类,但我需要一个驻留在UnitInst对象(表多对多)上的属性 我的班级: public class Unit { public long Id { get; set; } public string Name { get; set; } public string Description { get; set; } publ
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
}
公共类单元
{
公共长Id{get;set;}
公共字符串名称{get;set;}
公共字符串说明{get;set;}
公共虚拟ICollection UnitInsts{get;set;}
}
公共类研究所
{
公共长Id{get;set;}
公共字符串名称{get;set;}
公共虚拟ICollection UnitInsts{get;set;}
}
公共阶级团结主义
{
公共长Id{get;set;}
公共长单位ID{get;set;}
公共虚拟单元单元{get;set;}
公共长插入{get;set;}
公共虚拟指令指令{get;set;}
公共字符串IPv4{get;set;}//重要的属性
}
我的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
}
public class UnitDto
{
公共长Id{get;set;}
公共字符串名称{get;set;}
公共字符串说明{get;set;}
公共IEnumerable指令{get;set;}
}
公共类研究所
{
公共长Id{get;set;}
公共字符串名称{get;set;}
公共字符串IPv4{get;set;}//我需要在响应json中序列化此属性
}
我以这种方式映射,这没问题,但我无法从UnitInst类(多对多表)检索IPv4属性
CreateMap()
.ForMember(dto=>dto.Insts,opt=>opt.MapFrom(x=>x.UnitInsts.Select(y=>y.Inst.ToList()))
.references();
如何求解?通常,您将创建两个映射(
Unit
->UnitDto
和Inst
->InstDto
)并使用所显示的选择
技巧。但这仅适用于连接实体没有其他数据的情况,这里的情况并非如此
因此,您需要直接映射联接实体集合:
CreateMap<Unit, UnitDto>()
.ForMember(dst => dst.Insts, opt => opt.MapFrom(src => src.UnitInsts)); // <-- no Select
这里,AutoMapper用于将常规Inst
->instdt指定的Inst
成员映射到映射,并且显式映射目标Id
属性,因为源对象和“包含”对象都有同名的属性,在这种情况下,源具有优先级,但是您希望Id
成为Inst.Id
或instit
最后,Inst
->InstDTO
映射:
CreateMap<Inst, InstDTO>()
.ForMember(dst => dst.IPv4, opt => opt.Ignore());
CreateMap()
.ForMember(dst=>dst.IPv4,opt=>opt.Ignore());
此处缺少一些信息。有Inst
和Instrument
,还有UnitInst
和UnitInstrument
。这两对是同一件事吗?@方言对不起,我弄错了,我已经更新了问题,这里只有Inst类。它工作得很好,谢谢
cfg.CreateMap<UnitInst, InstDTO>()
.IncludeMembers(src => src.Inst) // needs `Inst` -> `InstDTO` map
.ForMember(dst => dst.Id, opt => opt.MapFrom(src => src.Inst.Id));
CreateMap<Inst, InstDTO>()
.ForMember(dst => dst.IPv4, opt => opt.Ignore());