Search code examples
c#sql-serverentity-frameworkidentityef-database-first

Insert value into non-identity key field : DB First


Ran into a small problem while working on EF 6 Database first approach.

When I try to insert a value into the key field of a table which is not set to be the Identity, I receive the following exception:

Cannot insert the value NULL into column 'emp_main_id',column does not allow nulls. INSERT fails.
The statement has been terminated.

I added the following code in the entity class to avoid the error

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int emp_main_id { get; set; }

but still could not get it working.

Below is the script to create the db table

    CREATE TABLE [dbo].[EmployeesMain] (
    [emp_main_id]          INT            NOT NULL,
    [emp_main_first]       NVARCHAR (40)  NOT NULL,
    [emp_main_middle]      NVARCHAR (40)  NULL,
    [emp_main_last]        NVARCHAR (40)  NOT NULL,
    [emp_main_dob]         DATE           NOT NULL,
    [emp_main_gender]      INT            DEFAULT ((1)) NOT NULL,
    [emp_main_type]        INT            DEFAULT ((0)) NOT NULL,
    [emp_main_email]       NVARCHAR (150) NOT NULL,
    [emp_main_password]    NVARCHAR (MAX) NOT NULL,
    [emp_main_designation] NVARCHAR (150) NULL,
    [emp_main_skill]       NVARCHAR (MAX) NULL,
    [emp_main_contract]    INT            DEFAULT ((0)) NOT NULL,
    [emp_main_lead]        NVARCHAR (81)  NULL,
    [emp_main_img]         NVARCHAR (MAX) NULL,
    [emp_main_doj]         DATE           DEFAULT ('01-JAN-2012') NULL,
    CONSTRAINT [emp_main_primary_key] PRIMARY KEY ([emp_main_id])
);

Any help on this will be appreciated.


Solution

  • Decided to write the answer myself.

    The problem was, since I had set the field as an identity earlier, the values for the field were being generated automatically. Even after removing the identity and updating the model from the database, this was not reset.

    So what I had to do was,

    1. Go to the .edmx file.
    2. Right click on the property "emp_main_id"
    3. Click on Properties
    4. Set StoreGeneratedPatter to None
    5. Save the model and rebuild the solution

    That's it. it gives me a non-identity key, with all the other constraints along with the option to explicitly enter a value for the field. Peace :)