'The value of 'Tag.UserId' is unknown when attempting to save changes. Efcore6 issue

I have below entities and defined model binder like below and when I try to add/update the data to tag table/entity I get error as: The value of 'Tag.UserId' is unknown when attempting to save changes. This is because the property is also part of a foreign key for which the principal entity in the relationship is not known.

This occurs when userId is 0,for other value it works

public class Tag
    {
        public int TagId { get; set; }
        public int UserId { get; set; }
        
        [ForeignKey("UserId")]
        public virtual User user { get; set; }
    }
    
     public partial class User
    {
        
        public int UserId { get; set; }
        public string UserName { get; set; }
        public virtual ICollection<Tag> Tags { get; set; }
    }

  modelBuilder.Entity<Tag>(entity =>
            {
                entity.HasKey(e => new { e.TagId, e.TagName });
                entity.Property(e => e.TagId).HasColumnName("TagId");
                entity.Property(e => e.TagName).HasColumnName("TagName");
                entity.HasOne(d => d.User)
                      .WithMany(p => p.Tags)
                      .HasForeignKey(f=>f.UserId)
                      .OnDelete(DeleteBehavior.ClientSetNull);
            });

code was working when we were using .netcore 3.1(efcore 3.1) and fails when we migrated to .net6(efcore 6)

PS: I see a similar issue here https://github.com/dotnet/efcore/issues/21954 but not any solution



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source