自动投影和联合

时间:2015-11-06 11:07:44

标签: c# entity-framework linq automapper automapper-2

我对union和automapper投影有问题。

我有两个实体:

public class Entity
{
    public DateTime ActionDate { get; set; }
    public int SomeProp { get; set; }
}

public class ExtendedEntity
{
    public DateTime ActionDate { get; set; }
    public int SomeProp { get; set; }
    public int SomeOtherProp { get; set; }
}

和投影:

public class EntityProjection
{
    public DateTime ActionDate { get; set; }
    public int SomeProp { get; set; }
    public int SomeOtherProp { get; set; }
    public string Source { get; set; }
}

我将实体映射到一个投影,实体没有SomeOtherProp所以我将0设置为它:

public class EntityProfile : Profile
{
    protected override void Configure()
    {
        CreateMap<ExtendedEntity, EntityProjection>()
            .ForMember(dest => dest.Source, opt => opt.MapFrom(src => "ext entity"));

        CreateMap<Entity, EntityProjection>()
            .ForMember(dest => dest.SomeOtherProp, opt => opt.MapFrom(src => 0))
            .ForMember(dest => dest.Source, opt => opt.MapFrom(src => "entity"));
    }
}

当我尝试使用下一个代码时,我收到错误:

 var entities = context.Set<Entity>()
            .Project().To<EntityProjection>();
 var extEntities = context.Set<ExtendedEntity>()
            .Project().To<EntityProjection>();
 var result = entities.Union(extEntities).OrderBy(p => p.ActionDate).ToList();

错误文本:“UserQuery + EntityProjection”类型出现在单个LINQ to Entities查询中的两个结构不兼容的初始化中。一种类型可以......

这意味着投影中的属性必须以相同的顺序初始化,我如何通过automapper设置投影属性初始化顺序?

1 个答案:

答案 0 :(得分:0)

答案非常晚,短版似乎是“你不能”。

我有完全相同的问题(Can I force Automapper to initialise properties in a certain order?)并最终在LINQ select语句中映射所有内容。

为方便起见,我在我的DTO(缩减代码)中将其设为静态方法:

Memory Limit Exceeded

然后你可以获得你的对象,作为一个IQueryable,简单地通过适当的静态方法传递它们(将一个选择附加到DTO - 或项目,因为它已知),然后是Union或Concat生成的IQueryables。

唯一的缺点是Automapper通常会处理递归自动化,虽然我很确定无论如何都不能很好地映射到SQL,所以你可能不会损失很多。

相关问题