如何搜索SQL数据库以防止重复的变量



我正在尝试创建一个问答网站,例如Quora或Stackoverflow。如何使用自定义方法搜索标记名是否已经存在,以便可以选择它,而不是创建重复。我已经有一个想法,应该看起来像这样:

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

,但我似乎无法将这种逻辑触及到Parsetag方法

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

如何将不存在的标签添加到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;
}

最新更新