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

时间:2017-12-04 13:49:33

标签: c# linq many-to-many

我正在尝试创建问答网站,例如quora或stackoverflow。我如何设置自定义方法来搜索tagName是否已经存在,因此它可以只选择它,而不是创建副本。我已经知道它应该看起来像这样:

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

1 个答案:

答案 0 :(得分:1)

如何仅在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;
}