我的视图模型如下:
File file = new File(Environment.getExternalStorageDirectory() + "/ExpensesApp/expensesData.xls");
实体:
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; }
}
我想将CarViewModel映射到Car Entity类型,如下所示:
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; }
}
在映射配置中,我想从CreateMap<CarViewModel, Car>()
.ForMember(dest => dest.Engine, src => src.Ignore());
映射到CarViewModel
。
但是如果引擎Car
那么映射应该被忽略。
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
Auto mapper中是否有此任务的扩展名。我已按上述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`
}
进行了尝试,它也将在src.Ignore()
期间忽略。
因此,我不想在更新期间映射空值。或者,它应保留为目标值
编辑:
AutoMapper配置:
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);
。 mapped
预期产出: