Search code examples
c#sqlmany-to-many

An unhandled exception occurred while trying to save new data


I'm trying to save the changes changes for a question and answer project I am creating. I can't save Tags because it returns an exception whenever I query if the data already exists.

 public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
        {
        }

    public DbSet<ApplicationUser> ApplicationUsers { get; set; }
    public DbSet<Question> Questions { get; set; }
    public DbSet<Tag> Tags { get; set; }
    public DbSet<QuestionTag> QuestionTags { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<QuestionTag>()
                    .HasKey(t => new { t.QuestionID, t.TagID });

        modelBuilder.Entity<QuestionTag>()
            .HasOne(qt => qt.Question)
            .WithMany(q => q.QuestionTags)
            .HasForeignKey(qt => qt.QuestionID);

        modelBuilder.Entity<QuestionTag>()
            .HasOne(qt => qt.Tag)
            .WithMany(t => t.QuestionTags)
            .HasForeignKey(qt => qt.TagID);
}

Here is the code I use to Parse new Data while querying if the Tags already exist.

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)
                .Select(x => new QuestionTag { Tag = new Tag { Name = x.Name } })
                .FirstOrDefault();

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

        }
            if (anyNewTags) _context.SaveChanges();
        return questionTags;
    }

But Instead, I get this Error when I try to parse in new Tags: InvalidOperationException: The property 'QuestionID' on entity type 'QuestionTag' has a temporary value. Either set a permanent value explicitly or ensure that the database is configured to generate values for this property.


Solution

  • The error directs you that you should set QuestionID property to establish assosication with Question entity. So try to set a value to QuestionId property.

    var newTag = new QuestionTag() { Tag = new Tag() { Name = tag }, QuestionId = questionId };
    _context.QuestionTags.Add(newTag);
    

    Note : I wrote questionId variable for making an example. You should set it with related ID of Question entity.