C# 在ASP.Net Framwork API中配置和使用AutoMapper
我试图在Asp.NETFrameworkAPI(非核心)中使用AutoMapper,当我尝试使用时,我的模型DTO会将所有属性都设置为null 我尝试了很多解决方案,很多都不推荐。因此,我的实际解决方案是:C# 在ASP.Net Framwork API中配置和使用AutoMapper,c#,asp.net,automapper,C#,Asp.net,Automapper,我试图在Asp.NETFrameworkAPI(非核心)中使用AutoMapper,当我尝试使用时,我的模型DTO会将所有属性都设置为null 我尝试了很多解决方案,很多都不推荐。因此,我的实际解决方案是: 创建一个配置类 从.edmx获取模型并创建DTO 创建配置文件 公共类MyProfile:Profile { 公共MyProfile() { CreateMap().ReverseMap(); } } 在控制器中使用AutoMapper 公共类MyController:ApiControl
公共类MyProfile:Profile
{
公共MyProfile()
{
CreateMap().ReverseMap();
}
}
公共类MyController:ApiController
{
只读IMapper映射器=自动映射器配置。\u映射器;
公共列表Get()
{
使用(var ctx=new DbEntities())
{
var src=ctx.User.ToList;
var dst=新列表();
src.ForEach(u=>dst.Add(mapper.Map(u));
}
}
}
现在,出于某种原因,我将dst列表中的所有对象都设置为null。例如,我在DB中有3个对象,当我调用这个方法时,我会检索3个DTO对象,但所有参数都为null。为什么?
谢谢我只看到了核心项目。你能帮我在我的Asp.NETWeb应用程序中实现这个吗?(我对.Net相当陌生)我只看到核心项目。你能帮我在我的Asp.NETWeb应用程序中实现这个吗?(我对.Net还很陌生)
public static class AutoMapperConfig
{
public static IMapper _mapper { get; set; }
public static void Register()
{
var mapperConfig = new MapperConfiguration(
config =>
{
config.AddProfile<MyProfile>();
}
);
_mapper = mapperConfig.CreateMapper();
}
}
protected void Application_Start()
{
...
AutoMapperConfig.RegisterMapping();
}
public class User
{
public string Name { get; set; }
public string Surname { get; set; }
public string Address { get; set; }
...
public string Email { get; set; }
}
public class UserDto
{
//I need only this 3
public string Name { get; set; }
public string Surname { get; set; }
public string Email { get; set; }
}
public class MyProfile : Profile
{
public MyProfile()
{
CreateMap<User, UserDto>().ReverseMap();
}
}
public class MyController : ApiController
{
readonly IMapper mapper = AutoMapperConfig._mapper;
public List<UserDto> Get()
{
using(var ctx = new DbEntities())
{
var src = ctx.User.ToList;
var dst = new List<UserDto>();
src.ForEach(u = > dst.Add(mapper.Map<UserDto>(u)));
}
}
}