0

我的视图模型如下:

public class CarViewModel
{
    public Guid Id { get; set; }
    public string CarName { get; set; }
    public List<EngineTypeViewModel> Engine { get; set; }
}

public class EngineTypeViewModel
{
    public int Id { get; set; }
    public string name { get; set; }
}

实体:

public class Car
{
    public Guid Id { get; set; }
    public string CarName { get; set; }
    public virtual ICollection<EngineType> Engine { get; set; }
}
public class EngineType
{
    public int Id { get; set; }
    public string name { get; set; }
}

我想将 CarViewModel 映射到 Car Entity 类型,如下所示:

CreateMap<CarViewModel, Car>()
    .ForMember(dest => dest.Engine, src => src.Ignore()); 

在映射配置中,我想从映射CarViewModelCar. 但是如果引擎count is 0那么映射应该被忽略。

CreateMap<CarViewModel, Car>()
    .ForMember(dest => dest.Engine, src => src.Ignore()); 
//Map only when src.Engine.Count > 0 other wise Ignore
// What should be my approach here??

这意味着在更新期间,当我使用GetById. 喜欢

public Update(CarViewModel model)
{
   var car = obj.GetById(model.Id);
   var mapped = map.Map(model,car); 

   //if the model.Engine.Count = 0 car.Engine 
   //should be same as mapped.Engine, there should not be mapping with the 
   //object(Engine) from the `CarViewModel`
}   

Auto mapper 中是否对此任务有任何扩展。我已经按照上面的方法尝试过,src.Ignore()它也会在此期间忽略ADD

所以,我不想在更新期间映射空值。或者,它应该保留为目标值

编辑:

自动映射器配置:

CreateMap<CarViewModel, Car>().ForMember(dest => dest.Engine, o =>
{
    o.Condition(src => src.Engine.Count > 0);

    //mapping
    o.MapFrom(src => src.Engine);
});

映射记录:

var carmodel = new CarViewModel();
carmodel.CarName = "Maruti";
carmodel.Id = Guid.NewGuid();

var carentity = new Car();
carentity.CarName = "Maruti";
carentity.Id = Guid.NewGuid();
carentity.Engine.Add(new EngineType { Id = 1, name = "PetrolEngine" });
carentity.Engine.Add(new EngineType { Id = 2, name = "DieselEngine" });
carentity.Engine.Add(new EngineType { Id = 3, name = "CranotEngine" });


var mapped = _mapper.Map(carmodel, carentity);

你可以看看mappedmapped.Engine is Empty

在此处输入图像描述

预期输出:

在此处输入图像描述

4

0 回答 0