C# 自动映射只需要字段
我使用AutoMapper映射类。我正在努力使用自动映射语法。 我有域类:C# 自动映射只需要字段,c#,.net,automapper,C#,.net,Automapper,我使用AutoMapper映射类。我正在努力使用自动映射语法。 我有域类: public class Club { public int Id { get; set; } public string Name { get; set; } public DateTime OpenDate { get; set; } public IEnumerable<Team&g
public class Club
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime OpenDate { get; set; }
public IEnumerable<Team> Teams { get; set; }
}
public class Team
{
public int Id { get; set; }
public string Name { get; set; }
public string Department { get; set; }
public IEnumerable<Player> Players { get; set; }
}
public class Player
{
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public int Age { get; set; }
public string Address { get; set; }
}
CreateMap<PlayerDTO, Player>();
CreateMap<TeamDTO, Team>();
CreateMap<ClubDTO, Club>();
如何仅设置映射
Player.Age
和Player.Addres
而不是所有字段所有类?我认为您应该忽略任何不希望映射的属性,如:
CreateMap<PlayerDTO, Player>();
.ForMember(x => x.Id, x => x.Ignore())
.ForMember(x => x.Name, x => x.Ignore());
.ForMember(x => x.Surname , x => x.Ignore());
CreateMap();
.ForMember(x=>x.Id,x=>x.Ignore())
.ForMember(x=>x.Name,x=>x.Ignore());
.ForMember(x=>x.姓氏,x=>x.Ignore());
请注意,这应该在automapper配置期间完成,而不是在调用
Map
方法时完成。您应该能够执行以下操作:\u mapper.Map(from,to).ForMember(x=>x.MyProperty,opt=>opt.Ignore())代码>
我还建议使用查看模型
。这对AutoMapper
有很大帮助,例如:
public class Player
{
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public int Age { get; set; }
public string Address { get; set; }
}
public class PlayerViewModel
{
public int Id{get; set;
//more fields that you can use in your views
}
这回答了你的问题吗?基本上,您应该在Map
之后调用ForMember
,但我不确定它是否会这样工作,因为Map
返回“to”是什么,这不太可能有ForMember
方法公平点。我有我的AutoMapper的自定义设置,所以我可以在视图模型的底部进行设置。我不记得正常的AutoMapper是如何工作的,但你可能是对的
CreateMap<PlayerDTO, Player>();
.ForMember(x => x.Id, x => x.Ignore())
.ForMember(x => x.Name, x => x.Ignore());
.ForMember(x => x.Surname , x => x.Ignore());
public class Player
{
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public int Age { get; set; }
public string Address { get; set; }
}
public class PlayerViewModel
{
public int Id{get; set;
//more fields that you can use in your views
}