亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用 Linq 的 Select 方法并將每個實體傳遞給 automapper

如何使用 Linq 的 Select 方法并將每個實體傳遞給 automapper

C#
元芳怎么了 2021-11-14 15:47:59
在我的 ASP.NET MVC 項目中,我有一個 HttpGET 方法,我需要從數據庫中獲取車輛列表。很簡單,直接獲取數據,傳遞列表即可查看。但是我正在學習 udemy(asp.net MVC 5 完整版)的教程,其中作者使用 Automapper 自動將對象與其 Dtos 映射。在本教程中,它是 Automapper 4.1 版,但我使用的是 7.x 版。因此,在我的 get 方法中,我無法理解如何編寫 Linq 查詢以獲取所有車輛并將每個車輛映射到其 dto 并作為列表發送。[HttpGet]public IEnumerable<VehicleDto> GetVehicles(){     return _context.Vehicles.ToList().Select(Mapper.Map<Vehicle,VehicleDto>(**How can I send each object here**));     //return _context.Vehicles.ToList();}我已經瀏覽了 Automapper 中的幫助文檔,但找不到合適的示例,或者我不明白如何應用該材料來解決我的問題,請幫助。
查看完整描述

2 回答

?
飲歌長嘯

TA貢獻1951條經驗 獲得超3個贊

假設_context.Vehicles.ToList()返回一個IList<Vehicle>,您可以執行以下操作:


[HttpGet]

public IEnumerable<VehicleDto> GetVehicles()

{

    return Mapper.Map<IList<Vehicle>, List<VehicleDto>>(_context.Vehicles.ToList());

}

這還假設您已經使用以下內容配置了從Vehicle到的映射VehicleDto:


cfg.CreateMap<Vehicle, VehicleDto>();

或者,您可以使用 LINQ 的 select 運算符并執行以下操作來調用Map單個項目而不是整個集合:


[HttpGet]

public IEnumerable<VehicleDto> GetVehicles()

{

    return _context.Vehicles.Select(v => Mapper.Map<Vehicle, VehicleDto>(v)).ToList();

}

更新: 切換Vehicle并VehicleDto反映 OP 在評論中顯示的信息,表明他將數據存儲Vehicle在數據庫中,并且他的方法應返回VehicleDto.


查看完整回答
反對 回復 2021-11-14
?
犯罪嫌疑人X

TA貢獻2080條經驗 獲得超4個贊

您之前是否定義了映射器類?


您在啟動時加載類。


App_Start 文件夾。創建一個名為 MapModelEntity.cs 的類 

public class MapModelEntity

{

    public static void RegisterMapping()

    {

        Mapper.Initialize(config =>

        {

          config.CreateMap<StatusEntity, StatusTypeModel>().ReverseMap(); // For bothways

          config.CreateMap<Vehicle, VehicleDto>() // For custom mapping

                .ForMember(dest => dest.Prop1,

                           opts => opts.MapFrom(src => src.Prop1)); 

        }

添加對 Global.asax 的引用


protected void Application_Start()

{

        GlobalConfiguration.Configure(WebApiConfig.Register);

        AreaRegistration.RegisterAllAreas();

        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

        RouteConfig.RegisterRoutes(RouteTable.Routes);

        BundleConfig.RegisterBundles(BundleTable.Bundles);

        **MapModelEntity.RegisterMapping();**

}


在控制器中


var Result = _context.Vehicles.ToList();

var Mapped = Mapper.Map<VehicleDto>(Result);


查看完整回答
反對 回復 2021-11-14
  • 2 回答
  • 0 關注
  • 282 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號