0

I need help with mapping entities. I want connect DAL and BL. I don´t know how to map collection.

Entity Team in DAL:

    namespace ICSapp.DAL.Entities
    {
            public class Team : ICSappEntityBase
            {


                    public string TeamName { get; set; }


                    public virtual ICollection<UserTeam> Members { get; set; }


                    public virtual ICollection<Post> Posts { get; set; }

        }

Same class Is in my BLL models.

and here Is a code for BLL mapper:

    namespace ICSapp.BL.Mapper
    {
           public static TeamModel MapTeamEntityToDTeamModel(Team entity)
            {
                    return new TeamModel
                    {
                            Id = entity.Id,
                            TeamName = entity.TeamName,
                            // Members = entity.Members ??
                           // Posts = entity.Posts ??
                    };
            }

         public static Team MapTeamModelToTeamEntity(TeamModel model)
         {
                    return new IngredientEntity
                    {
                            Id = model.Id,
                            TeamName = model.TeamName,
                            //Members = model.Members ??
                           // Posts = model Posts ??
                    };
            }

        }

So how to map a collection? Thanks

PS : I need to do it manually.

1 Answers1

0
public static TeamModel MapTeamEntityToDTeamModel(Team entity)
{
    return new TeamModel
    {
        Id = entity.Id,
        TeamName = entity.TeamName,
        Members = entity.Members.Select(x => MapTeamUserEntityToTeamUserModel(x)).ToList()
     };
}
public static TeamUserModel MapTeamUserEntityToTeamUserModel(TeamUser entity)
{
    return new TeamUserModel
    {
        Id = entity.Id,
        UserName = entity.UserName,
        // etc. etc.
     };
}

repeat for posts.

Really though, invest in a pitch to use Automapper. It does this all automatically, and it can integrate directly with EF's IQueryable based functionality using the ProjectTo<T> so that it can project your ViewModels directly within EF queries. The manual approach is not as efficient, prone to lazy-load hits, and re-inventing an already well-rounded wheel.

Steve Py
  • 26,149
  • 3
  • 25
  • 43