Get & ldquo; Can not insert NULL value in column & rdquo; when you try to register with the .Add () method using DbContext. Please check my POCO and save the method

advertisements

Used code first and everything appears to work apart from the below which also worked before when I used ObjectContext and called context.PCBuilds.AddObject(pcBuild) but after switching to DbContext it's giving me the error.

EFDbContext context = new EFDbContext();

        public ActionResult Index()
        {
            PCBuild pcBuild = new PCBuild();
            pcBuild.BuildID = 34245;
            pcBuild.BuildName = "Test99";
            pcBuild.MarkUp = 25;
            pcBuild.BDetails = new List<BDetail>();

            context.PCBuilds.Add(pcBuild);

            //repository.PCBuilds.Attach(pcBuild);

            context.SaveChanges();

            return View();
        }

Giving me the: Cannot insert the value NULL into column 'BuildID', table 'C:\USERS\ADMIN\DOCUMENTS\VISUAL STUDIO 2010\PROJECTS\NEOCART\NEOCART.WEBUI\APP_DATA\NEODBX.MDF.dbo.PCBuilds'; column does not allow nulls. INSERT fails. Where as BuildID was clearly set before the SaveChanges is called. Appears that calling the .Add(pcBuild) doesn't add the populated object for some reason and when savechanges is called it attempts to insert an empty PCBuild ?

Here are the POCO's

public class PCBuild
    {
        [Key]
        public int BuildID { get; set; }

        public string BuildName { get; set; }

        public string Socket { get; set; }

        public decimal? MarkUp {get; set;}

        [InverseProperty("PCBuild")]
        public virtual ICollection<BDetail> BDetails { get; set; }

    }

public class BDetail
{
    [Key]
    public int LineID { get; set; }

    [ForeignKey("PCBuild")]
    public int BuildID { get; set; }

    [ForeignKey("Product")]
    public int ProductID { get; set; }

    public bool? IsSelected { get; set; }

    [InverseProperty("BDetails")]
    public virtual PCBuild PCBuild { get; set; }

    [InverseProperty("BDetails")]
    public virtual Product Product { get; set; }

}


Use StoreGeneratedAttribute on the PCBuild.BuildID property. It is not only a key but IDENTITY field.

UPDATE Actually, it should be [DatabaseGenerated(DatabaseGenerationOption.Identity)] annotation. The article linked above describes early CTP version.

UPDATE 2 Wait, the key is being generated by the app, it is not an identity column in database? Change annotation to [DatabaseGenerated(DatabaseGenerationOption.None)], re-create the context and rebuild the application.