Identity insert when adding many to many relations EF

c# entity-framework entity-framework-6

Question

i made a many to many relationship and the table was created with Classes and Users for a gym web app,but when i try to insert values to that table i get SqlException: Cannot insert explicit value for identity column in table 'classes' when IDENTITY_INSERT is set to OFF.

My models are Class

 public class Class
        {
            [Key]
            public int ClassID { get; set; }
            ...
            public List<UserClass> userClasses { get; set; }
      }

User:

public class User
        {
            [Key]
            public int UserID{ get; set; }
            ...
            public List<UserClass> userClasses { get; set; }
      }

Where they merge:

public class UserClass
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public long UserClassID { get; set; }

        public int UserID { get; set; }
        public int ClassID { get; set; }

        public User user { get; set; }
        public Class @class { get; set; }
    }

my context class modelbiulder function:

protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<UserClass>()
               .HasKey(x => new { x.UserID, x.ClassID });

            //If you name your foreign keys correctly, then you don't need this.
            modelBuilder.Entity<UserClass>()
                .HasOne(uc => uc.user)
                .WithMany(p => p.userClasses)
                .HasForeignKey(uc => uc.UserID);

            modelBuilder.Entity<UserClass>()
                .HasOne(uc => uc.@class)
                .WithMany(t => t.userClasses)
                .HasForeignKey(uc => uc.ClassID);
        }

and this function that i use with ajax

public IActionResult BookTheClass(int ClassID)
        {
            User user = _context.users.Find(_auth.User.UserID);
            Class selectedClass = _context.classes.Find(ClassID);

            selectedClass.userClasses = new List<UserClass>() {
                    new UserClass{
                   user=user,
                    @class=selectedClass
                    }
            };
            _context.classes.Add(selectedClass);
            _context.SaveChanges();

            return PartialView("~/Views/PartialViews/ClassBooked.cshtml");
        }

The other similar questions had a model builder problem that i dont have.

1
0
4/10/2020 2:11:33 AM

Popular Answer

An identity column will keep track of the next free number, and you do not need to generate the ClassId by yourself. The new id can be fetched by SELECT SCOPE_IDENTITY()

If you really want to insert value to an identity column(not recommended) then you would have to switch on the Identity Insert property of your table. See the below SQL to do the same

SET IDENTITY_INSERT classes ON
0
4/10/2020 2:25:21 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow