AllocSystems
AllocSystems

Reputation: 1079

How to search SQL database to prevent duplicated variables

I am trying to create a question and answer website, like quora or stackoverflow. How can I put in a custom method to search if the tagName already exists, so it can just select it, rather than create a duplicate. I already have an idea it should look something like this:

var objectExists = _context.Tag.Find(a => a.Name == tag);
if (objectExists == null)
{
   _context.QuestionTag.Add(new QuestionTag(){Tag = new Tag(){ Name = tag });
}  

But I can't seem to incoporate that logic into the parseTag method

 public async Task BuildQuestion(string title, string body, string tags, ApplicationUser user)
            {
                var question = new Question
                {
                    Title = title,
                    Body = body,
                    QuestionTags = ParseTags(tags),
                    User = user
                };
                _context.Add(question);
                await _context.SaveChangesAsync();
            }

    public List<QuestionTag> ParseTags(string tags)
    {
        var tagList = tags.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries).ToList();
        var questionTags = new List<QuestionTag>();

        foreach(var tag in tagList)
        {
            questionTags.Add(new QuestionTag()
            {
                Tag = new Tag(){Name = tag}}
            );
        }
        return questionTags;
    }

Upvotes: 0

Views: 61

Answers (1)

Mithgroth
Mithgroth

Reputation: 1212

How about only adding the non-existing tags to the database in ParseTags()?

public List<QuestionTag> ParseTags(string tags)
{
    var tagList = tags.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries).ToList();
    var questionTags = new List<QuestionTag>();
    var anyNewTags = false; //to see if we have to SaveChanges()

    foreach(var tag in tagList)
    {
        //You should do the check and add your tags here
        var objectExists = _context.Tag.Find(a => a.Name == tag);
        if (objectExists == null)
        {
           //tag doesn't exist
           //create a new tag, add it to db
           //also add it to the tag list

           var newTag = new QuestionTag() { Tag = new Tag() { Name = tag } };
           _context.QuestionTag.Add(newTag);
           questionTags.Add(newTag);

           //there is a new tag, we have to call SaveChanges()
           anyNewTags = true;
        }
        else
        {
           //tag exists, just grab it, no need to add anything.
           questionTags.Add(objectExists);
        }
    }

    //do we have new tags, do we need to call SaveChanges()?
    if (anyNewTags) _context.SaveChanges();

    return questionTags;
}

Upvotes: 1

Related Questions