I have three tables Tags, TagCategories and SiteCategory.

TagCategories has two columns; one is the index of Tags and the other is the index from SiteCategory; that means that between Tags and SiteCategory, there is a many-to-many relationship.

When I do scaffold for my database in the .NET Core 8 projects the scaffold builds two models one for Tags and the other for SiteCategory and the model builder is:

Tag

modelBuilder.Entity<Tag>(entity =>
        {
            entity.HasKey(e => e.Indx);

            entity.Property(e => e.Tag1)
                .HasMaxLength(50)
                .HasColumnName("Tag");

            entity.HasMany(d => d.Categories).WithMany(p => p.Tags)
                .UsingEntity<Dictionary<string, object>>(
                    "TagCategory",
                    r => r.HasOne<SiteCategory>().WithMany()
                        .HasForeignKey("CategoryId")
                        .OnDelete(DeleteBehavior.ClientSetNull)
                        .HasConstraintName("FK_TagCategories_SiteCategory"),
                    l => l.HasOne<Tag>().WithMany()
                        .HasForeignKey("TagId")
                        .OnDelete(DeleteBehavior.ClientSetNull)
                        .HasConstraintName("FK_TagCategories_Tags"),
                    j =>
                    {
                        j.HasKey("TagId", "CategoryId");
                        j.ToTable("TagCategories");
                        j.IndexerProperty<int>("TagId").HasColumnName("TagID");
                        j.IndexerProperty<int>("CategoryId").HasColumnName("CategoryID");
                    });
        });

SiteCategory :

modelBuilder.Entity<SiteCategory>(entity =>
        {
            entity.HasKey(e => e.Indx);

            entity.ToTable("SiteCategory");

            entity.Property(e => e.Category).HasMaxLength(18);
            entity.Property(e => e.ShowInSystem)
                .IsRequired()
                .HasDefaultValueSql("((1))");
        });

I am trying to create a new tag and add and I have the SiteCategory index, so I want to add it to the TagCategories table.

My function:

public bool addTagAndTagCategory(Tag tag, int? categoryID)
{
        try
        {
            var siteCat = db.SiteCategories.Where(cat => cat.Indx == categoryID).FirstOrDefault();
            siteCat.Tags.Add(tag);
            db.Add(tag);
            //var TagCategory = new Dictionary<string, object>
            //    {
            //        { "TagId", tag.Indx },
            //        { "CategoryId", siteCat.Indx }
            //    };
            //db.Attach(TagCategory);
            db.SaveChanges();
            var res = tag.Indx != 0 ? true : false;
            return res;
        }
        catch
        {
            throw;
        }
}

I get this error:

SqlException: Cannot insert explicit value for identity column in table 'SiteCategory' when IDENTITY_INSERT is set to OFF

0

There are 0 answers