Adding tags support in the blogging system

The fields required in the Post entity to incorporate Tags support in posts will be covered in this section. Let's start the activity by including the fields required to persist tag information in the Post model, as follows:

    public class Post
{
// Code removed for brevity
[NotMapped]
public ICollection<Tag> Tags { get; set; }
[NotMapped]
public ICollection<int> TagIds { get; set; }
[NotMapped]
public string TagNames { get; set; }
}

The tag information required in the Posts list view is listed as follows:

  • Tags : This tag information is a filtered list of tags associated with the Post
  • TagNames : This tag information is a filtered tag name in a comma-separated string

Let's incorporate the code required to expose the filtered Tag list flattened to a string named TagNames in the GetAllPostsQuery object. The flattened string value will be flattened using string.Join() as shown in the following code:

    public class GetAllPostsQuery : QueryBase, 
IGetAllPostsQuery<GetAllPostsQuery>
{
// Code removed for brevity
public IEnumerable<Post> Handle()
{
// Code removed for brevity
posts.ForEach(x =>
{
var tags = (from tag in Context.Tags
join tagPost in Context.TagPosts
on tag.Id equals tagPost.TagId
where tagPost.PostId == x.Id
select tag).ToList();
x.TagNames = string.Join(", ",
tags.Select(y => y.Name).ToArray());

});
return posts;
}

public async Task<IEnumerable<Post>> HandleAsync()
{
// Code removed for brevity
posts.ForEach(x =>
{
var tags = (from tag in Context.Tags
join tagPost in Context.TagPosts
on tag.Id equals tagPost.TagId
where tagPost.PostId == x.Id
select tag).ToList();
x.TagNames = string.Join(", ",
tags.Select(y => y.Name).ToArray());

});
return posts;
}
}

The tags will be listed in the Posts Index view, displayed as follows:

 

We have seen the support provided for tags in the blogging system. In the next section, let's explore how the default transactional behavior works.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset