重构包含多对多关系的Controller

时间:2017-12-08 14:03:24

标签: c# refactoring many-to-many

我正在关注制作博客的教程,我想知道如何重构一些看似乱七八糟的代码。特别是在标记中解析时的多对多关系。有没有更好的方法将其减少为控制器上的较小功能?

select itemid, LTRIM(RTRIM(content))
from objects
where itemid = 100 and content like '%remove%'

1 个答案:

答案 0 :(得分:1)

不是在控制器上创建新方法,而是可以封装解析和搜索类中标记的所有行为,可能是这样的:

public class Tags
{
    private readonly IEnumerable<Tag> contextTags;
    private readonly string rawTags;

    public Tags(string tags, IEnumerable<Tag> contextTags)
    {
        this.rawTags = tags ?? string.Empty;
        this.contextTags = contextTags;
    }

    public IEnumerable<Tag> ToList()
    {
        List<Tag> tags = new List<Tag>();

        string[] tagNames = this.rawTags.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

        foreach (string tagName in tagNames)
        {
            tags.Add(this.GetTag(tagName));
        }

        return tags;
    }

    private Tag GetTag(string tagName)
    {
        return this.contextTags.FirstOrDefault(x => x.Name == tagName) ?? new Tag { Name = tagName };
    }
}

然后控制器上的Create方法变为:

public ActionResult Create(int? id, string title, string body, DateTime datetime, string tags)
{
    Post post = GetPost(id);
    post.Title = title;
    post.Body = body;
    post.Tags.Clear();

    Tags tagsList = new Tags(tags, this._context.Tags);

    post.Tags = tagsList.ToList();
}