.net mvc Entity framework primary key is null after Add to context for an identity property

For a dbset which I have created

    public Int32 Id { get; set; }

    [Display(Name ="Book Name")]
    public string BookName { get; set; }

    [DisplayFormat(DataFormatString ="{0:dd/MM/yy}")]
    [Display(Name ="Published date")]
    public DateTime? PublishedDate { get; set; }

    [Display(Name ="Added To Library")]
    [DisplayFormat(DataFormatString ="{0:dd/MM/yy}")]
    public DateTime? AddedDate { get; set; }

    [Display(Name ="Books in Library")]
    public int NoOfCopies { get; set; }

    public Genere Genere { get; set; }

    [Display(Name ="Genere")]
    public byte GenereId { get; set; }

I then tried to create a new record and add it to dbcontext

     _context.Books.Add(book);

but getting the error cannot add null to Id which is the primary key when

      _context.SaveChanges();

2 answers

  • answered 2018-11-08 07:00 Udara Kasun

    Add Key Attribute

    [Key]
    public Int32 Id { get; set; }
    

  • answered 2018-11-08 07:02 AmirNorouzpour

    You must use Key Attribute or use Id convention after entity name "BookId"