简体   繁体   中英

Cannot insert explicit value for identity column in table '' error in WCF service

Issue


I want my SQL database table primary key ID to increment by 1 automatically when i add a row to the table.

I am using a WCF service and in the DAL ( Data Access Layer ) I am trying to add a row into the database but it keeps passing '0' in as the primary key ID.

Code


This is my DAL, as you can see I am setting all the values. NOTE HOLIDAY_ID is the incremented id for the SQL table and i am not passing it any value:

public void AddHoliday(string STARTDATE, string ENDDATE)
{

    HOLIDAY_EVENT _newHolidayEvent = new HOLIDAY_EVENT
    {
        USER_ID = 1,
        HOLIDAY_TITLE = "Test1",
        HOLIDAY_START = Convert.ToDateTime(STARTDATE),
        HOLIDAY_END = Convert.ToDateTime(ENDDATE),
        HOLIDAY_EVENT_STATE_ID = 2
    };

    _ENTITY.HOLIDAY_EVENT.Add(_newHolidayEvent);
    _ENTITY.SaveChanges();
}

Here is the design of my SQL table:

在此处输入图片说明

Here is the way i set the increment of the HOLIDAY_ID:

在此处输入图片说明

Conclusion


In my DAL what do I need to pass to HOLIDAY_ID for the ID to increment automatically?

Did you set DatabaseGenerated(DatabaseGeneratedOption.Identity) in your model ?

for example:

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int HOLIDAY_ID { get; set; }

HOLIDAY_ID should be available after SaveChanges() call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM