代码之家  ›  专栏  ›  技术社区  ›  AllocSystems

修复查询现有数据时的错误

  •  0
  • AllocSystems  · 技术社区  · 8 年前

    我试图确定一个变量是否已经存在,所以我不会创建重复的。但我不断地发现一个错误:

    无法从系统转换。林克。易读的

    以下是导致错误的代码:

    public List<QuestionTag> ParseTags(string tags)
    {
        var tagList = tags.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList();
        var questionTags = new List<QuestionTag>();
        var anyNewTags = false;
    
    foreach (var tag in tagList)
    {
        var tagExists = _context.Tags.Where(x => x.Name == tag);
        if (tagExists == null)
        {
            var newTag = new QuestionTag() { Tag = new Tag() { Name = tag } };
            _context.QuestionTags.Add(newTag);
            questionTags.Add(newTag);
    
            anyNewTags = true;
        }
        else
        {
            questionTags.Add(tagExists); // ERROR OCCURS HERE
        }
    
    }
    if (anyNewTags) _context.SaveChanges();
    return questionTags;
    

    }

    1 回复  |  直到 8 年前
        1
  •  1
  •   Sunil evesnight    8 年前

    您的查询尚未生成结果,因此出现错误。为了使其屈服,请使用其中之一。ToList()、First()或FirstOrDefault()。

    假设结果为列表,则使用:

    questionTags.AddRange(tagExists.ToList()); 
    

    假设生成单个对象,则使用:

    questionTags.Add(tagExists.First()); 
    

    ====编辑=======

    您的问题标签属于类型 List<QuestionTag> ,但当您添加 tagExists ,这是类型 Tags .

    所以改变这个,

    var tagExists = _context.Tags.Where(x => x.Name == tag).Select(x => new QuestionTag { Tag = new Tag { Name = x.Name} }).FirstOrDefault();