几乎每个数据库表都有审核戳记列(CreatedById,CreatedOn,ModifiedById,ModifiedOn),我们也希望使用Automapper投影将其映射到视图模型。
因此,我们有大量的视图模型,它们的映射表达式在各处都有复制:
.ForMember(vm => vm.CreatedByName, opt => opt.MapFrom(entity => entity.UserProfile.FirstName + " " + entity.UserProfile.LastName))
.ForMember(vm => vm.ModifiedByName, opt => opt.MapFrom(entity => entity.UserProfile1.FirstName + " " + entity.UserProfile1.LastName))
实体类确实继承了AuditStamps类:
public class AuditStamps
{
public virtual string CreatedByName { get; set; }
public virtual string ModifiedByName { get; set; }
}
E.G。:
public partial class Item : AuditStamps, IAuditStamps
该界面包括UserProfile
参考的导航属性:
public interface IAuditStamps
{
UserProfile UserProfile { get; set; }
UserProfile UserProfile1 { get; set; }
int CreatedById { get; set; }
string CreatedByName { get; set; }
DateTime CreatedOn { get; set; }
int ModifiedById { get; set; }
string ModifiedByName { get; set; }
DateTime ModifiedOn { get; set; }
}
使用AuditStamps
属性定义视图模型:
public class ItemViewModel : IAuditStamps
{
public AuditStamps AuditStamps { get; set; }
}
我正在创建一个Expression语句,该语句可以基于接口作为源来重用:
public Expression<Func<IAuditStamps, AuditStamps>> MapAuditStamps
{
get
{
return entity => new AuditStamps {
CreatedByName = entity.UserProfile.FirstName + " " + entity.UserProfile.LastName,
ModifiedByName = entity.UserProfile1.FirstName + " " + entity.UserProfile1.LastName
};
}
}
然后尝试像这样使用它:
.ForMember(dest => dest.AuditStamps, option => option.MapFrom(MapAuditStamps))
但是出现设计时错误:
cannot convert from 'System.Linq.Expressions.Expression<System.Func<IAuditStamps, AuditStamps>>' to 'AutoMapper.IValueResolver<Item, ItemViewModel, object>'
在Expressions
方面,我并不是最强的。。。不确定我是否只是语法上的错误,或者这种方法是否可能?