首先使用EF代码的AutoMapper无限循环

时间:2018-12-05 15:31:24

标签: c# entity-framework automapper asp.net-mvc-viewmodel

我有以下课程(一对一关系Asset-TrackingDevice):

public class Asset
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public TrackingDevice TrackingDevice { get; set; }

    }

public class TrackingDevice
    {
        public int Id { get; set; }
        public string Imei { get; set; }
        public int? AssetId { get; set; }
        public Asset Asset { get; set; }
    }

viewModels非常相似:

public class AssetViewModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int? TrackingDeviceId { get; set; }
        public TrackingDeviceViewModel TrackingDevice { get; set; }

    }
public class TrackingDeviceViewModel
    {
        public int Id { get; set; }       
        public string Imei { get; set; }
        public AssetViewModel Asset { get; set; }
        public string AssetId { get; set; }
    }

映射:

CreateMap<Asset, AssetViewModel>()
                .ForMember(d => d.TrackingDevice, map => map.Ignore());
CreateMap<AssetViewModel, Asset>()
                .ForMember(d => d.TrackingDevice, map => map.Ignore());
CreateMap<AssetViewModel, Asset>()
                .ReverseMap();
CreateMap<TrackingDevice, TrackingDeviceViewModel>()
                .ForMember(d => d.Asset, map => map.Ignore());
CreateMap<TrackingDeviceViewModel, TrackingDevice>()
                .ForMember(d => d.Asset, map => map.Ignore());
CreateMap<TrackingDevice, TrackingDeviceViewModel>()
                .ReverseMap();

当我执行数据库查询以获取TrackingDevices时, 我收到一个错误消息,因为在映射中,跟踪设备中的资产还包括跟踪设备,等等。

我为获取跟踪设备而执行的查询是:

var trackingDevices = _appContext.TrackingDevices
         .Include(td => td.Asset)
         .ToListAsync();
var trackingMapper = Mapper.Map<IEnumerable<TrackingDeviceViewModel>>(trackingDevices);

我读到通过包含Map.Ignore可以解决此问题,但它也不起作用,有人知道我的错误吗?

0 个答案:

没有答案