如何使ProjectTo正确地映射不同的派生类型,而不将它们向下转换为基础类型?
使用Mapper.Map可以正常工作,但使用ProjectTo无法正常工作。
源类:(EntityFramework模型)
public class FailureAlertEntity : AlertEntity
{
public FailureAlertEntity(int id, string description) : base(id)
{
Description = description;
}
public string Description { get; set; }
}
public class AlertEntity
{
public AlertEntity(int id)
{
ID = id;
}
public int ID { get; set; }
}
目标类(DTO模型):
public class FailureAlert : Alert
{
public FailureAlert(int id, string description) : base(id)
{
Description = description;
}
public string Description { get; set; }
}
public class Alert
{
public Alert(int id)
{
ID = id;
}
public int ID { get; set; }
}
有多个从AlertEntity和Alert派生的类,我想在不将派生类型降为其基础类型的情况下映射这两种类型之间。
配置:
Mapper.Initialize(cfg => {
cfg.CreateMap<AlertEntity, Alert>()
.Include<FailureAlertEntity, FailureAlert>();
cfg.CreateMap<FailureAlertEntity, FailureAlert>();
});
测试代码:
var entities = new List<AlertEntity>()
{
new FailureAlertEntity(1, "foo"),
new FailureAlertEntity(2, "bar")
};
var alerts = entities.AsQueryable().ProjectTo<Alert>();
结果:
ProjectTo似乎不考虑列表中项目的类型,而是将它们强制转换为列表本身的类型。如果列表的类型是FailureAlertEntity,则显然可以工作,但列表可能包含其他派生自AlertEntity的类型。
如果我想使用Mapper.Map对对象执行相同的操作,那么完全没问题:
var faEntity = new FailureAlertEntity(1, "asd");
var dto = Mapper.Map<Alert>(faEntity);
结果:
我该如何使用ProjectTo映射类型,就像Mapper.Map一样?我以为它们都会使用相同的配置。
.Select(Mapper.Map<Alert>).
可以工作,但没有办法进行过滤而不收集数据库中的所有项。我想使用类似于yourQuery.ProjectTo<Alert>().Where(x => x.Prop == ...).ToList()
的东西。它在SQL中完美地转换为WHERE
,但不会创建正确的实例。如何解决这个要求? - Sebastian Schumann