Base solution for your next web application
Starts in:
01 DAYS
01 HRS
01 MIN
01 SEC
Open Closed

How does mapping from model to dto really works? #1583


User avatar
0
stefanbelo created

I know that it is used AutoMapper library, but I cannot find in my project how it is done.

Having this model:

[Table("ZptArticles")]
    public class Article : CreationAuditedEntity<int, User>
    {
        public virtual string Title { get; set; }

        public virtual string Text { get; set; }

        public virtual int ViewCount { get; set; }

        public virtual ICollection<Comment> Comments { get; set; }

        public virtual ICollection<ArticleTag> Tags { get; set; }

        public Article()
        {
        }

        public Article(string title, string text)
        {
            Title = title;
            Text = text;
        }
    }

and this Dto:

[AutoMapFrom(typeof(Article))]
    public class ArticleDto : CreationAuditedEntityDto
    {
        public string Title { get; set; }

        public string Text { get; set; }

        public int ViewCount { get; set; }

        public int CommentCount { get; set; }

        public string CreatorUserName { get; set; }
    }

It is clear that EF return CreatorUser as well, so from CreatorUser.Name, we have got maybe our: CreatorUserName in Dto mapping.

If I would like to return Dto with number of comments, how would I do so?

Is it possible (for EF) to avoid loading all comments for the article, as I do not want full comments content, but just number of article's comments?


1 Answer(s)
  • User Avatar
    0
    gpcaretti created

    You have to remove the attribute

    [AutoMapFrom(typeof(Article))]
    

    and create your own map.

    From Abp v. 1.0.0 this can be done in Abp MVC and SPA template in the "Application" project. See YourProjectApplicationModule.cs. There you can find something like:

    public override void PreInitialize()
            {
                Configuration.Modules.AbpAutoMapper().Configurators.Add(mapper =>
                {
                    //Add your custom AutoMapper mappings here...
                    //mapper.CreateMap<,>()
                   ...
                });
            }
    

    Gp