【问题标题】:How to map Entities from DAL to BL如何将实体从 DAL 映射到 BL
【发布时间】:2019-08-25 13:32:18
【问题描述】:

我需要有关映射实体的帮助。我想连接 DAL 和 BL。我不知道如何映射集合。

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; }

        }

我的 BLL 模型中有相同的类。

这里是 BLL 映射器的代码:

    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 ??
                    };
            }

        }

那么如何映射一个集合呢? 谢谢

PS:我需要手动完成。

【问题讨论】:

标签: entity-framework mapping code-first data-access-layer


【解决方案1】:
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.
     };
}

重复发帖。

真的,投资一个使用 Automapper 的宣传。这一切都是自动完成的,它可以使用ProjectTo&lt;T&gt; 直接与 EF 的基于IQueryable 的功能集成,以便它可以直接在 EF 查询中投影您的 ViewModel。手动方法效率不高,容易出现延迟加载,并且重新发明了一个已经很完善的轮子。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多