AutoMapper EF,带有接口和嵌套集合

时间:2017-04-26 18:36:37

标签: c# entity-framework asp.net-web-api2 automapper dto

这是我的设置,在它们出现错误和描述之后。

接口

public interface IUser
{
    int Id { get; set; }
    string Firstname { get; set; }
    string Lastname { get; set; }
    string Email { get; set; }
    string Fullname { get; }
}

public interface IPost
{
    int Id { get; set; }

    String Description { get; set; }

    DateTime CreatedDate { get; set; }

    int? UserId { get; set; }

    IUser User { get; set; }

    ICollection<IComment> Comments { get; set; }
}

public interface IComment
{
    int Id { get; set; }
    string Description { get; set; }
    DateTime CreatedDate { get; set; }
    int? PostId { get; set; }
    int? UserId { get; set; }
    IUser User { get; set; }
}

AutoMapper配置:

        Mapper.Initialize(cfg => cfg.CreateMap<IUser, DAL.User>());
        Mapper.Initialize(cfg => cfg.CreateMap<IComment, DAL.Comment>());
        Mapper.Initialize(cfg => cfg.CreateMap<IPost, DAL.Post>()
            .ForMember(d => d.User, m => m.MapFrom(s => s.User))
            .ForMember(d => d.UserId, m => m.MapFrom(s => s.User.Id))
            .ForMember(d => d.Comments, m => m.MapFrom(s => s.Comments))
        );

        Mapper.AssertConfigurationIsValid();

EF代码:

    public IEnumerable<IPost> GetPosts()
    {
        IQueryable<DAL.Post> query = dbSet.Posts.Include("Comments");
        var result = Mapper.Map<IEnumerable<IPost>>(query);
        return result;
    }

错误:

{“HiThere.DAL.User上的以下属性无法映射:\ n \ t \ tUser \ n添加自定义映射表达式,忽略,添加自定义解析程序或修改目标类型HiThere.DAL.User。\ nContext: \ n \ tMapping到属性用户从HiThere.Model.Common.IUser到HiThere.DAL.User \ n抛出类型'AutoMapper.AutoMapperConfigurationException'的异常被抛出。“}

说明

我在ASP.NET WebAPI2项目中使用AutoMapper来在DAL和Models之间映射数据。出于某种原因,我在使用嵌套对象时无法进行正确的映射。 任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

实际上我通过将所有cfg.CreateMap添加到单个Mapper.Inizialize来修复它。我的错。希望有人会发现这很有用。

        Mapper.Initialize(cfg =>
            {
                cfg.CreateMap<DAL.Post, IPost>()
                    .ForMember(d => d.User, m => m.MapFrom(s => s.User))
                    .ForMember(d => d.UserId, m => m.MapFrom(s => s.User.Id))
                    .ForMember(d => d.Comments, m => m.MapFrom(s => s.Comments))
                ;
                cfg.CreateMap<IUser, DAL.User>().ReverseMap();
                cfg.CreateMap<IComment, DAL.Comment>().ReverseMap();
            } 
        );

        Mapper.AssertConfigurationIsValid();