通过Automapper LINQ投影中的和接口跨实体重用表达式

时间:2019-05-20 17:57:53

标签: c# entity-framework linq-to-sql automapper projection

几乎每个数据库表都有审核戳记列(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方面,我并不是最强的。。。不确定我是否只是语法上的错误,或者这种方法是否可能?

0 个答案:

没有答案