Search code examples
linqmany-to-many

Fixing an error while querying for existing an data


I am trying to determine if a variable already exists, so I won't create a duplicate. But I keep getting an error:

Cannot convert from System.Linq.IQueryable

Here's the code that results in the error:

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;

}


Solution

  • You tagExists query hasn't yielded a result yet, hence the error. In order to make it yield, use either .ToList(), First() or FirstOrDefault().

    Assuming it results in a list, then use:

    questionTags.AddRange(tagExists.ToList()); 
    

    Assuming it results in a single object, then use:

    questionTags.Add(tagExists.First()); 
    

    ====== Edit =======

    Your questionTags is of type List<QuestionTag>, but when you add tagExists, this is of type Tags.

    So change this,

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