Blazor insert into sql including unique id which should be part of query

Jacques Labuschagne 21 Reputation points
2022-11-20T09:11:33.31+00:00

Hallo

I've been battling for some time now, using code first migration and to create database and using blazor server to update data to SQL, but for some reason which I cannot figure out the id which is the primary key for sql is also included in part of the insert into query from c#. it should not include the id column this is auto generated by sql. but this is only happening on one of the tables, which is the employee table, the department is correct.

Below the query from both.

INSERT INTO [Employees] ([Id], [DateTimeCreated], [DepartmentId], [HireDate], [IsActive], [ModifiedBy], [ModifiedOn], [Name], [Occupation], [Surname])

VALUES (@p0, @p1, @p2, @p3, @p4, @p5, @p6, @p7, @p8, @p9);

INSERT INTO [Departments] ([DateTimeCreated], [IsActive], [ModifiedBy], [ModifiedOn], [Name], [TimeScheduleId])

VALUES (@p0, @p1, @p2, @p3, @p4, @p5);

Included the migrations and snapshot which shows the id in Employee is haskey. (I also did try adding the [key] and [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
to the model but still includes the id in the insert.

namespace FlexProOfficeBlaze.Shared.Employees  
{  
    [Table("Employees")]  
    public class Employee : DatabaseAbstractDefaults  
    {  
        //[Key]  
        //[DatabaseGenerated(DatabaseGeneratedOption.Identity)]  
        public int Id { get; set; }  

        [Required(ErrorMessage = "Name is required")]  
        [Column(TypeName = "varchar(50)")]  
        public string? Name { get; set; }  

        [Required(ErrorMessage = "Surname is required", AllowEmptyStrings = true)]  
        [Column(TypeName = "varchar(50)")]  
        public string? Surname { get; set; }  

        [DisplayFormat(DataFormatString = "{yyyy-MM-dd}",  
                        ApplyFormatInEditMode = true)]  
        public DateTime HireDate { get; set; } = DateTime.Now;  
        public string? Occupation { get; set; }        

        public int DepartmentId { get; set; }  
        public Department? Department { get; set; }  

        //static string[] ViewNames = {"HiredWithin", "" };  
    }  
}  

namespace FlexProOfficeBlaze.Shared.Departments  
{  
    [Table("Departments")]  
    public class Department : DatabaseAbstractDefaults  
    {  
        public int Id { get; set; }  

        [Required (ErrorMessage="Name Cannot be Empty")]  
        [Column(TypeName = "varchar(50)")]  
        public string? Name { get; set; } = String.Empty;  
        public int TimeScheduleId { get; set; } = 0;               
    }  
}  

// <auto-generated />  
using System;  
using FlexProOfficeBlaze.Server.Data;  
using Microsoft.EntityFrameworkCore;  
using Microsoft.EntityFrameworkCore.Infrastructure;  
using Microsoft.EntityFrameworkCore.Metadata;  
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;  

#nullable disable  

namespace FlexProOfficeBlaze.Server.Migrations  
{  
    [DbContext(typeof(DataContext))]  
    partial class DataContextModelSnapshot : ModelSnapshot  
    {  
        protected override void BuildModel(ModelBuilder modelBuilder)  
        {  
#pragma warning disable 612, 618  
            modelBuilder  
                .HasAnnotation("ProductVersion", "6.0.10")  
                .HasAnnotation("Relational:MaxIdentifierLength", 128);  

            SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder, 1L, 1);  

            modelBuilder.Entity("FlexProOfficeBlaze.Shared.Banking.AccountType", b =>  
                {  
                    b.Property<int>("Id")  
                        .ValueGeneratedOnAdd()  
                        .HasColumnType("int");  

                    SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"), 1L, 1);  

                    b.Property<DateTime>("DateTimeCreated")  
                        .HasColumnType("datetime2");  

                    b.Property<bool>("IsActive")  
                        .HasColumnType("bit");  

                    b.Property<string>("ModifiedBy")  
                        .HasColumnType("varchar(50)");  

                    b.Property<DateTime>("ModifiedOn")  
                        .HasColumnType("datetime2");  

                    b.Property<string>("Type")  
                        .HasColumnType("varchar(50)");  

                    b.HasKey("Id");  

                    b.ToTable("AccountTypes");  
                });  

            modelBuilder.Entity("FlexProOfficeBlaze.Shared.Banking.BankDetail", b =>  
                {  
                    b.Property<int>("Id")  
                        .ValueGeneratedOnAdd()  
                        .HasColumnType("int");  

                    SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"), 1L, 1);  

                    b.Property<string>("AccountNr")  
                        .HasColumnType("varchar(50)");  

                    b.Property<int?>("AccountTypeId")  
                        .HasColumnType("int");  

                    b.Property<int?>("BankNameId")  
                        .HasColumnType("int");  

                    b.Property<string>("BranchName")  
                        .HasColumnType("varchar(50)");  

                    b.Property<DateTime>("DateTimeCreated")  
                        .HasColumnType("datetime2");  

                    b.Property<bool>("IsActive")  
                        .HasColumnType("bit");  

                    b.Property<string>("ModifiedBy")  
                        .HasColumnType("varchar(50)");  

                    b.Property<DateTime>("ModifiedOn")  
                        .HasColumnType("datetime2");  

                    b.HasKey("Id");  

                    b.HasIndex("AccountTypeId");  

                    b.HasIndex("BankNameId");  

                    b.ToTable("BankDetails");  
                });  

            modelBuilder.Entity("FlexProOfficeBlaze.Shared.Banking.BankName", b =>  
                {  
                    b.Property<int>("Id")  
                        .ValueGeneratedOnAdd()  
                        .HasColumnType("int");  

                    SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"), 1L, 1);  

                    b.Property<string>("AddtionalField")  
                        .HasColumnType("varchar(50)");  

                    b.Property<DateTime>("DateTimeCreated")  
                        .HasColumnType("datetime2");  

                    b.Property<bool>("International")  
                        .HasColumnType("bit");  

                    b.Property<bool>("IsActive")  
                        .HasColumnType("bit");  

                    b.Property<string>("ModifiedBy")  
                        .HasColumnType("varchar(50)");  

                    b.Property<DateTime>("ModifiedOn")  
                        .HasColumnType("datetime2");  

                    b.Property<string>("Name")  
                        .HasColumnType("varchar(50)");  

                    b.Property<string>("UniversalBranchCode")  
                        .HasColumnType("varchar(50)");  

                    b.HasKey("Id");  

                    b.ToTable("BankNames");  
                });  

            modelBuilder.Entity("FlexProOfficeBlaze.Shared.Clockings.Clocking", b =>  
                {  
                    b.Property<int>("Id")  
                        .ValueGeneratedOnAdd()  
                        .HasColumnType("int");  

                    SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"), 1L, 1);  

                    b.Property<DateTime>("DateTimeCreated")  
                        .HasColumnType("datetime2");  

                    b.Property<int>("EmployeeId")  
                        .HasColumnType("int");  

                    b.Property<DateTime>("In")  
                        .HasColumnType("datetime2");  

                    b.Property<bool>("IsActive")  
                        .HasColumnType("bit");  

                    b.Property<string>("ModifiedBy")  
                        .HasColumnType("varchar(50)");  

                    b.Property<DateTime>("ModifiedOn")  
                        .HasColumnType("datetime2");  

                    b.Property<DateTime>("Out")  
                        .HasColumnType("datetime2");  

                    b.HasKey("Id");  

                    b.HasIndex("EmployeeId");  

                    b.ToTable("Clockings");  
                });  

            modelBuilder.Entity("FlexProOfficeBlaze.Shared.Clockings.TimeSchedule", b =>  
                {  
                    b.Property<int>("Id")  
                        .ValueGeneratedOnAdd()  
                        .HasColumnType("int");  

                    SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"), 1L, 1);  

                    b.Property<DateTime>("DateTimeCreated")  
                        .HasColumnType("datetime2");  

                    b.Property<bool>("IsActive")  
                        .HasColumnType("bit");  

                    b.Property<string>("ModifiedBy")  
                        .HasColumnType("varchar(50)");  

                    b.Property<DateTime>("ModifiedOn")  
                        .HasColumnType("datetime2");  

                    b.Property<string>("TimeScheduleName")  
                        .HasColumnType("varchar(50)");  

                    b.HasKey("Id");  

                    b.ToTable("TimeSchedules");  
                });  

            modelBuilder.Entity("FlexProOfficeBlaze.Shared.Clockings.WorkingDayTime", b =>  
                {  
                    b.Property<int>("Id")  
                        .ValueGeneratedOnAdd()  
                        .HasColumnType("int");  

                    SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"), 1L, 1);  

                    b.Property<TimeSpan>("AfternoonTeaEnd")  
                        .HasColumnType("time");  

                    b.Property<TimeSpan>("AfternoonTeaStart")  
                        .HasColumnType("time");  

                    b.Property<DateTime>("DateTimeCreated")  
                        .HasColumnType("datetime2");  

                    b.Property<int>("DayOfWeek")  
                        .HasColumnType("int");  

                    b.Property<bool>("IsActive")  
                        .HasColumnType("bit");  

                    b.Property<TimeSpan>("LunchEnd")  
                        .HasColumnType("time");  

                    b.Property<TimeSpan>("LunchStart")  
                        .HasColumnType("time");  

                    b.Property<TimeSpan>("MorningTeaEnd")  
                        .HasColumnType("time");  

                    b.Property<TimeSpan>("MorningTeaStart")  
                        .HasColumnType("time");  

                    b.Property<TimeSpan>("ShiftEndTime")  
                        .HasColumnType("time");  

                    b.Property<TimeSpan>("ShiftStartTime")  
                        .HasColumnType("time");  

                    b.Property<int>("TimeScheduleId")  
                        .HasColumnType("int");  

                    b.HasKey("Id");  

                    b.ToTable("WorkingDayTimes");  
                });  

            modelBuilder.Entity("FlexProOfficeBlaze.Shared.Departments.Department", b =>  
                {  
                    b.Property<int>("Id")  
                        .ValueGeneratedOnAdd()  
                        .HasColumnType("int");  

                    SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"), 1L, 1);  

                    b.Property<DateTime>("DateTimeCreated")  
                        .HasColumnType("datetime2");  

                    b.Property<bool>("IsActive")  
                        .HasColumnType("bit");  

                    b.Property<string>("ModifiedBy")  
                        .HasColumnType("varchar(50)");  

                    b.Property<DateTime>("ModifiedOn")  
                        .HasColumnType("datetime2");  

                    b.Property<string>("Name")  
                        .IsRequired()  
                        .HasColumnType("varchar(50)");  

                    b.Property<int>("TimeScheduleId")  
                        .HasColumnType("int");  

                    b.HasKey("Id");  

                    b.ToTable("Departments");  
                });  

            modelBuilder.Entity("FlexProOfficeBlaze.Shared.Employees.Employee", b =>  
                {  
                    b.Property<int>("Id")  
                        .ValueGeneratedOnAdd()  
                        .HasColumnType("int");  

                    SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"), 1L, 1);  

                    b.Property<DateTime>("DateTimeCreated")  
                        .HasColumnType("datetime2");  

                    b.Property<int>("DepartmentId")  
                        .HasColumnType("int");  

                    b.Property<DateTime>("HireDate")  
                        .HasColumnType("datetime2");  

                    b.Property<bool>("IsActive")  
                        .HasColumnType("bit");  

                    b.Property<string>("ModifiedBy")  
                        .HasColumnType("varchar(50)");  

                    b.Property<DateTime>("ModifiedOn")  
                        .HasColumnType("datetime2");  

                    b.Property<string>("Name")  
                        .IsRequired()  
                        .HasColumnType("varchar(50)");  

                    b.Property<string>("Occupation")  
                        .HasColumnType("nvarchar(max)");  

                    b.Property<string>("Surname")  
                        .IsRequired()  
                        .HasColumnType("varchar(50)");  

                    b.HasKey("Id");  

                    b.HasIndex("DepartmentId");  

                    b.ToTable("Employees");  
                });  

            modelBuilder.Entity("FlexProOfficeBlaze.Shared.Employees.Salary", b =>  
                {  
                    b.Property<int>("Id")  
                        .ValueGeneratedOnAdd()  
                        .HasColumnType("int");  

                    SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"), 1L, 1);  

                    b.Property<DateTime>("DateTimeCreated")  
                        .HasColumnType("datetime2");  

                    b.Property<int>("EmployeeId")  
                        .HasColumnType("int");  

                    b.Property<decimal>("HourlyRate")  
                        .HasColumnType("decimal(18,2)");  

                    b.Property<bool>("IsActive")  
                        .HasColumnType("bit");  

                    b.Property<string>("ModifiedBy")  
                        .HasColumnType("varchar(50)");  

                    b.Property<DateTime>("ModifiedOn")  
                        .HasColumnType("datetime2");  

                    b.Property<decimal>("MonthlySalary")  
                        .HasColumnType("decimal(18,2)");  

                    b.HasKey("Id");  

                    b.ToTable("Salaries");  
                });  

            modelBuilder.Entity("FlexProOfficeBlaze.Shared.Vendors.Address", b =>  
                {  
                    b.Property<int>("Id")  
                        .ValueGeneratedOnAdd()  
                        .HasColumnType("int");  

                    SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"), 1L, 1);  

                    b.Property<string>("Address1")  
                        .HasColumnType("varchar(50)");  

                    b.Property<string>("AddressType")  
                        .HasColumnType("varchar(50)");  

                    b.Property<string>("City")  
                        .HasColumnType("varchar(50)");  

                    b.Property<string>("Country")  
                        .HasColumnType("varchar(50)");  

                    b.Property<DateTime>("DateTimeCreated")  
                        .HasColumnType("datetime2");  

                    b.Property<bool>("IsActive")  
                        .HasColumnType("bit");  

                    b.Property<string>("ModifiedBy")  
                        .HasColumnType("varchar(50)");  

                    b.Property<DateTime>("ModifiedOn")  
                        .HasColumnType("datetime2");  

                    b.Property<string>("Province")  
                        .HasColumnType("varchar(50)");  

                    b.Property<int>("VendorId")  
                        .HasColumnType("int");  

                    b.Property<string>("ZipCode")  
                        .HasColumnType("varchar(50)");  

                    b.HasKey("Id");  

                    b.HasIndex("VendorId")  
                        .IsUnique();  

                    b.ToTable("Addresses");  
                });  

            modelBuilder.Entity("FlexProOfficeBlaze.Shared.Vendors.ContactDetail", b =>  
                {  
                    b.Property<int>("Id")  
                        .ValueGeneratedOnAdd()  
                        .HasColumnType("int");  

                    SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"), 1L, 1);  

                    b.Property<DateTime>("Birthday")  
                        .HasColumnType("datetime2");  

                    b.Property<string>("CellPhone")  
                        .HasColumnType("varchar(50)");  

                    b.Property<DateTime>("DateTimeCreated")  
                        .HasColumnType("datetime2");  

                    b.Property<string>("Designation")  
                        .HasColumnType("varchar(50)");  

                    b.Property<string>("Email")  
                        .HasColumnType("varchar(50)");  

                    b.Property<string>("FirstName")  
                        .HasColumnType("varchar(50)");  

                    b.Property<bool>("IsActive")  
                        .HasColumnType("bit");  

                    b.Property<string>("LandLine")  
                        .HasColumnType("varchar(50)");  

                    b.Property<string>("LastName")  
                        .HasColumnType("varchar(50)");  

                    b.Property<string>("ModifiedBy")  
                        .HasColumnType("varchar(50)");  

                    b.Property<DateTime>("ModifiedOn")  
                        .HasColumnType("datetime2");  

                    b.Property<string>("PhoneExtention")  
                        .HasColumnType("varchar(50)");  

                    b.Property<int>("VendorId")  
                        .HasColumnType("int");  

                    b.HasKey("Id");  

                    b.HasIndex("VendorId")  
                        .IsUnique();  

                    b.ToTable("ContactDetails");  
                });  

            modelBuilder.Entity("FlexProOfficeBlaze.Shared.Vendors.Vendor", b =>  
                {  
                    b.Property<int>("Id")  
                        .ValueGeneratedOnAdd()  
                        .HasColumnType("int");  

                    SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"), 1L, 1);  

                    b.Property<string>("Branch")  
                        .IsRequired()  
                        .HasColumnType("varchar(50)");  

                    b.Property<DateTime>("DateTimeCreated")  
                        .HasColumnType("datetime2");  

                    b.Property<int>("DefaultContactId")  
                        .HasColumnType("int");  

                    b.Property<string>("Email")  
                        .HasColumnType("varchar(50)");  

                    b.Property<bool>("IsActive")  
                        .HasColumnType("bit");  

                    b.Property<string>("MapUrl")  
                        .HasColumnType("varchar(50)");  

                    b.Property<string>("ModifiedBy")  
                        .HasColumnType("varchar(50)");  

                    b.Property<DateTime>("ModifiedOn")  
                        .HasColumnType("datetime2");  

                    b.Property<string>("Name")  
                        .IsRequired()  
                        .HasColumnType("varchar(50)");  

                    b.Property<string>("Notes")  
                        .HasColumnType("varchar(50)");  

                    b.Property<string>("PhoneNr")  
                        .HasColumnType("varchar(50)");  

                    b.Property<string>("VatNr")  
                        .HasColumnType("varchar(50)");  

                    b.Property<string>("Website")  
                        .HasColumnType("varchar(50)");  

                    b.HasKey("Id");  

                    b.ToTable("Vendors");  
                });  

            modelBuilder.Entity("FlexProOfficeBlaze.Shared.Banking.BankDetail", b =>  
                {  
                    b.HasOne("FlexProOfficeBlaze.Shared.Banking.AccountType", "AccountType")  
                        .WithMany()  
                        .HasForeignKey("AccountTypeId");  

                    b.HasOne("FlexProOfficeBlaze.Shared.Banking.BankName", "BankName")  
                        .WithMany()  
                        .HasForeignKey("BankNameId");  

                    b.Navigation("AccountType");  

                    b.Navigation("BankName");  
                });  

            modelBuilder.Entity("FlexProOfficeBlaze.Shared.Clockings.Clocking", b =>  
                {  
                    b.HasOne("FlexProOfficeBlaze.Shared.Employees.Employee", "employee")  
                        .WithMany()  
                        .HasForeignKey("EmployeeId")  
                        .OnDelete(DeleteBehavior.Cascade)  
                        .IsRequired();  

                    b.Navigation("employee");  
                });  

            modelBuilder.Entity("FlexProOfficeBlaze.Shared.Employees.Employee", b =>  
                {  
                    b.HasOne("FlexProOfficeBlaze.Shared.Departments.Department", "Department")  
                        .WithMany()  
                        .HasForeignKey("DepartmentId")  
                        .OnDelete(DeleteBehavior.Cascade)  
                        .IsRequired();  

                    b.Navigation("Department");  
                });  

            modelBuilder.Entity("FlexProOfficeBlaze.Shared.Vendors.Address", b =>  
                {  
                    b.HasOne("FlexProOfficeBlaze.Shared.Vendors.Vendor", null)  
                        .WithOne("Address")  
                        .HasForeignKey("FlexProOfficeBlaze.Shared.Vendors.Address", "VendorId")  
                        .OnDelete(DeleteBehavior.Cascade)  
                        .IsRequired();  
                });  

            modelBuilder.Entity("FlexProOfficeBlaze.Shared.Vendors.ContactDetail", b =>  
                {  
                    b.HasOne("FlexProOfficeBlaze.Shared.Vendors.Vendor", null)  
                        .WithOne("ContactDetail")  
                        .HasForeignKey("FlexProOfficeBlaze.Shared.Vendors.ContactDetail", "VendorId")  
                        .OnDelete(DeleteBehavior.Cascade)  
                        .IsRequired();  
                });  

            modelBuilder.Entity("FlexProOfficeBlaze.Shared.Vendors.Vendor", b =>  
                {  
                    b.Navigation("Address");  

                    b.Navigation("ContactDetail");  
                });  
#pragma warning restore 612, 618  
        }  
    }  
}  


using System;  
using Microsoft.EntityFrameworkCore.Migrations;  

#nullable disable  

namespace FlexProOfficeBlaze.Server.Migrations  
{  
    public partial class initial : Migration  
    {  
        protected override void Up(MigrationBuilder migrationBuilder)  
        {  
            migrationBuilder.CreateTable(  
                name: "AccountTypes",  
                columns: table => new  
                {  
                    Id = table.Column<int>(type: "int", nullable: false)  
                        .Annotation("SqlServer:Identity", "1, 1"),  
                    Type = table.Column<string>(type: "varchar(50)", nullable: true),  
                    DateTimeCreated = table.Column<DateTime>(type: "datetime2", nullable: false),  
                    ModifiedBy = table.Column<string>(type: "varchar(50)", nullable: true),  
                    ModifiedOn = table.Column<DateTime>(type: "datetime2", nullable: false),  
                    IsActive = table.Column<bool>(type: "bit", nullable: false)  
                },  
                constraints: table =>  
                {  
                    table.PrimaryKey("PK_AccountTypes", x => x.Id);  
                });  

            migrationBuilder.CreateTable(  
                name: "BankNames",  
                columns: table => new  
                {  
                    Id = table.Column<int>(type: "int", nullable: false)  
                        .Annotation("SqlServer:Identity", "1, 1"),  
                    International = table.Column<bool>(type: "bit", nullable: false),  
                    Name = table.Column<string>(type: "varchar(50)", nullable: true),  
                    UniversalBranchCode = table.Column<string>(type: "varchar(50)", nullable: true),  
                    AddtionalField = table.Column<string>(type: "varchar(50)", nullable: true),  
                    DateTimeCreated = table.Column<DateTime>(type: "datetime2", nullable: false),  
                    ModifiedBy = table.Column<string>(type: "varchar(50)", nullable: true),  
                    ModifiedOn = table.Column<DateTime>(type: "datetime2", nullable: false),  
                    IsActive = table.Column<bool>(type: "bit", nullable: false)  
                },  
                constraints: table =>  
                {  
                    table.PrimaryKey("PK_BankNames", x => x.Id);  
                });  

            migrationBuilder.CreateTable(  
                name: "Departments",  
                columns: table => new  
                {  
                    Id = table.Column<int>(type: "int", nullable: false)  
                        .Annotation("SqlServer:Identity", "1, 1"),  
                    Name = table.Column<string>(type: "varchar(50)", nullable: false),  
                    TimeScheduleId = table.Column<int>(type: "int", nullable: false),  
                    DateTimeCreated = table.Column<DateTime>(type: "datetime2", nullable: false),  
                    ModifiedBy = table.Column<string>(type: "varchar(50)", nullable: true),  
                    ModifiedOn = table.Column<DateTime>(type: "datetime2", nullable: false),  
                    IsActive = table.Column<bool>(type: "bit", nullable: false)  
                },  
                constraints: table =>  
                {  
                    table.PrimaryKey("PK_Departments", x => x.Id);  
                });  

            migrationBuilder.CreateTable(  
                name: "Salaries",  
                columns: table => new  
                {  
                    Id = table.Column<int>(type: "int", nullable: false)  
                        .Annotation("SqlServer:Identity", "1, 1"),  
                    EmployeeId = table.Column<int>(type: "int", nullable: false),  
                    MonthlySalary = table.Column<decimal>(type: "decimal(18,2)", nullable: false),  
                    HourlyRate = table.Column<decimal>(type: "decimal(18,2)", nullable: false),  
                    DateTimeCreated = table.Column<DateTime>(type: "datetime2", nullable: false),  
                    ModifiedBy = table.Column<string>(type: "varchar(50)", nullable: true),  
                    ModifiedOn = table.Column<DateTime>(type: "datetime2", nullable: false),  
                    IsActive = table.Column<bool>(type: "bit", nullable: false)  
                },  
                constraints: table =>  
                {  
                    table.PrimaryKey("PK_Salaries", x => x.Id);  
                });  

            migrationBuilder.CreateTable(  
                name: "TimeSchedules",  
                columns: table => new  
                {  
                    Id = table.Column<int>(type: "int", nullable: false)  
                        .Annotation("SqlServer:Identity", "1, 1"),  
                    TimeScheduleName = table.Column<string>(type: "varchar(50)", nullable: true),  
                    DateTimeCreated = table.Column<DateTime>(type: "datetime2", nullable: false),  
                    ModifiedBy = table.Column<string>(type: "varchar(50)", nullable: true),  
                    ModifiedOn = table.Column<DateTime>(type: "datetime2", nullable: false),  
                    IsActive = table.Column<bool>(type: "bit", nullable: false)  
                },  
                constraints: table =>  
                {  
                    table.PrimaryKey("PK_TimeSchedules", x => x.Id);  
                });  

            migrationBuilder.CreateTable(  
                name: "Vendors",  
                columns: table => new  
                {  
                    Id = table.Column<int>(type: "int", nullable: false)  
                        .Annotation("SqlServer:Identity", "1, 1"),  
                    Name = table.Column<string>(type: "varchar(50)", nullable: false),  
                    Branch = table.Column<string>(type: "varchar(50)", nullable: false),  
                    VatNr = table.Column<string>(type: "varchar(50)", nullable: true),  
                    Email = table.Column<string>(type: "varchar(50)", nullable: true),  
                    Website = table.Column<string>(type: "varchar(50)", nullable: true),  
                    PhoneNr = table.Column<string>(type: "varchar(50)", nullable: true),  
                    DefaultContactId = table.Column<int>(type: "int", nullable: false),  
                    Notes = table.Column<string>(type: "varchar(50)", nullable: true),  
                    MapUrl = table.Column<string>(type: "varchar(50)", nullable: true),  
                    DateTimeCreated = table.Column<DateTime>(type: "datetime2", nullable: false),  
                    ModifiedBy = table.Column<string>(type: "varchar(50)", nullable: true),  
                    
Blazor
Blazor
A free and open-source web framework that enables developers to create web apps using C# and HTML being developed by Microsoft.
1,378 questions
0 comments No comments
{count} votes

Accepted answer
  1. AgaveJoe 26,186 Reputation points
    2022-11-20T17:02:59.587+00:00

    You did not share the most important bits which are any error messages, the actual code that invokes SaveChanges(), and what DatabaseAbstractDefaults is. Perhaps Id is Department Id? I made a basic code first app using your models without DatabaseAbstractDefaults (since I have no idea what it is) and using standard naming conventions. The code just works.

    Simply populate the model(s), Add(), then SaveChanges().

    Models

        public class Employee   
        {  
            public int EmployeeId { get; set; }  
      
            public string? Name { get; set; }  
      
            public string? Surname { get; set; }  
      
            public DateTime HireDate { get; set; } = DateTime.Now;  
            public string? Occupation { get; set; }  
      
            public int DepartmentId { get; set; }  
            public Department? Department { get; set; }  
      
        }  
      
        public class Department  
        {  
            public int DepartmentId { get; set; }  
      
            public string? Name { get; set; } = String.Empty;  
            public int TimeScheduleId { get; set; } = 0;  
        }  
    

    The two DbSet to the context.

            public DbSet<Employee>? Employees { get; set; }  
            public DbSet<Department>? Departments { get; set; }  
    

    A method to save the data.

    public async Task<Employee> GetEmployeesTest()  
    {  
        Department department = new Department()  
        {  
            Name = "IT"  
        };  
      
        _context.Departments.Add(department);  
        await _context.SaveChangesAsync();  
      
        Employee employee = new Employee()  
        {  
            DepartmentId = 1,  
            HireDate = DateTime.Now,  
            Name = "Hello",  
            Occupation = "IT",  
            Surname = "World"  
        };  
      
        _context.Employees.Add(employee);  
        await _context.SaveChangesAsync();  
      
        return employee;  
    }  
    

    The SQL

    INSERT INTO "Departments" ("Name", "TimeScheduleId")  
    VALUES (@p0, @p1);  
      
    INSERT INTO "Employees" ("DepartmentId", "HireDate", "Name", "Occupation", "Surname")  
    VALUES (@p0, @p1, @p2, @p3, @p4);  
    

    Any getting start with Entity Framework tutorial covers these basics.

    Basic Save

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Jacques Labuschagne 21 Reputation points
    2022-11-21T06:51:08.41+00:00

    Hallo

    Thanks for the answer, I eventually found the error, simple mistake but so we learn. The issue was error below, but in short I didn't realise that I accidentally made a typing error and providing a id value in the input select which was linked incorrectly, ef then ignores the auto generated primary from sql and providing one in the query to update sql.

    But for reference below:

    Error:

    INSERT INTO [Employees] ([Id], [DateTimeCreated], [DepartmentId], [HireDate], [IsActive], [ModifiedBy], [ModifiedOn], [Name], [Occupation], [Surname])

    VALUES (@p0, @p1, @p2, @p3, @p4, @p5, @p6, @p7, @p8, @p9);
    Exception thrown: 'Microsoft.Data.SqlClient.SqlException' in System.Private.CoreLib.dll
    Exception thrown: 'Microsoft.Data.SqlClient.SqlException' in System.Private.CoreLib.dll
    Exception thrown: 'Microsoft.EntityFrameworkCore.DbUpdateException' in Microsoft.EntityFrameworkCore.Relational.dll
    Exception thrown: 'Microsoft.EntityFrameworkCore.DbUpdateException' in System.Private.CoreLib.dll
    Exception thrown: 'Microsoft.EntityFrameworkCore.DbUpdateException' in System.Private.CoreLib.dll
    Exception thrown: 'Microsoft.EntityFrameworkCore.DbUpdateException' in System.Private.CoreLib.dll
    Exception thrown: 'Microsoft.EntityFrameworkCore.DbUpdateException' in System.Private.CoreLib.dll
    Exception thrown: 'Microsoft.EntityFrameworkCore.DbUpdateException' in System.Private.CoreLib.dll
    Exception thrown: 'Microsoft.EntityFrameworkCore.DbUpdateException' in Microsoft.EntityFrameworkCore.dll
    Exception thrown: 'Microsoft.EntityFrameworkCore.DbUpdateException' in System.Private.CoreLib.dll
    Exception thrown: 'Microsoft.EntityFrameworkCore.DbUpdateException' in System.Private.CoreLib.dll
    Microsoft.EntityFrameworkCore.Update: Error: An exception occurred in the database while saving changes for context type 'FlexProOfficeBlaze.Server.Data.DataContext'.
    Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while saving the entity changes. See the inner exception for details.
    ---> Microsoft.Data.SqlClient.SqlException (0x80131904): Cannot insert explicit value for identity column in table 'Employees' when IDENTITY_INSERT is set to OFF. >

    Mistaken I've made in the inputselect binding.

     <div class="input-group">  
                            <InputSelect id="department" @bind-Value="***employee.Id***">  //Should have been employee.DepartmentId                               
                                @foreach (var dept in departments)  
                                {  
                                <option value="@dept.Id">@dept.Name</option>  
                                }                    
                            </InputSelect>    
                                    <button class="btn btn-outline-secondary" type="button" @onclick="DepartmentModalClicked">New</button>  
        </div>  
    

    Thanks for taking the time to answer.

    Regards,

    0 comments No comments