Let me show the error:
Cannot insert the value NULL into column 'Id', table 'TCCDatabase.dbo.ProfessionalModels'; column does not allow nulls. INSERT fails.
I got this error when trying to insert n record into my database using a database created by my EF application.
I think it's happening because my database Id column is not auto-incrementing.
My question is: Why are my Id Columns not auto-incrementing?
One of my models:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace TCCApplication.Models
{
public class ProfessionalModel
{
public int Id { get; set; }
public string Name { get; set; }
[Column(TypeName = "DateTime2")]
public DateTime BirthDate { get; set; }
public int PhoneNumber { get; set; }
public string Profession { get; set; }
public UserAddressModel UserAddressModel { get; set; }
public UserAccountModel UserAccountModel { get; set; }
public ProfessionalModel() { }
}
}
My context class:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Linq;
using System.Web;
using TCCApplication.Models;
namespace TCCApplication.EntityFramework
{
public class TCCDatabase : DbContext
{
public DbSet<UserAccountModel> UserAccountContext { get; set; }
public DbSet<ProfessionalModel> ProfessionalContext { get; set; }
public DbSet<UserAddressModel> UserAddressContext { get; set; }
public TCCDatabase()
{}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<ProfessionalModel>().Property(a => a.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
modelBuilder.Entity<UserAccountModel>().Property(a => a.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
modelBuilder.Entity<UserAddressModel>().Property(a => a.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
}
}
}