unable to add new record to a table with "auto increment" set using mvc

خالد الريمي 21 Reputation points
2021-07-27T11:36:47.227+00:00

Hello
I am trying to add a new record using class

    public partial class TP004Master
    {
        public int APP_ID { get; set; }
        public string Site_Coord_ID { get; set; }
        public string PTL_ID { get; set; }
        public string TTL_ID { get; set; }
        public string STL_ID { get; set; }
        public string Create_By { get; set; }
        public Nullable<System.DateTime> Created_on { get; set; }
        public string modified_By { get; set; }
        public Nullable<System.DateTime> modified_on { get; set; }
    }

In database , the APP_ID is a primary key and it is auto incremented.

//save into TP004Master
                TP004Master tp004Master = new TP004Master();

                tp004Master.Site_Coord_ID = Engs.Coord_ID;
                tp004Master.PTL_ID = Engs.PTL_ID;
                tp004Master.TTL_ID = Engs.TTL_ID;
                tp004Master.STL_ID = Engs.STL_ID;
                tp004Master.Create_By = "1";
                tp004Master.Created_on = DateTime.UtcNow.AddHours(3);

                DB.TP004Master.Add(tp004Master);
                DB.SaveChanges();

It throws this error :
"SqlException: Cannot insert explicit value for identity column in table 'TP004Master' when IDENTITY_INSERT is set to OFF."

when I debug, I find that the tp004Master.APP_ID get the value : 0
Though I didn't set it to any value any where.

ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,491 questions
{count} votes

Accepted answer
  1. Yijing Sun-MSFT 7,081 Reputation points
    2021-07-28T02:53:39.953+00:00

    Hi @خالد الريمي ,
    It' s a EF problem not MVC.I think you need to add the [DatabaseGenerated(..)] annotation to indicate an IDENTITY column in the table.Just like this:

     [DatabaseGenerated(DatabaseGeneratedOption.Identity)]  
    

    You need to either make sure the value in the object mapped to this column is not modified or marked as modified.
    Best regards,
    Yijing Sun


    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our  documentation  to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.