Search code examples
c#sqlentity-frameworknullableconstraintexception

My SQL table is set to allow NULL for this column, but when I run it, it says it cannot be NULL. What/Why/How?


so I have quite the odd predicament here. My SQL table is set to allow nulls for my ZipCode column, like so:

CREATE TABLE [dbo].[Companies]
(
    [CompanyId] BIGINT IDENTITY(1,1) NOT NULL PRIMARY KEY, 
    [Name] NVARCHAR(100) NOT NULL, 
    [Address]     NVARCHAR (100) NULL,
    [City]        NVARCHAR (50)  NOT NULL,
    [State]       NVARCHAR (2)   NOT NULL,
    [ZipCode]     INT   NULL,
    [PhoneNum]    BIGINT  NULL,
    [CreatedDate] DATETIME2 NOT NULL DEFAULT GetDate()
)

This should let me have ZipCode's value as NULL, right? Well, apparently not....

I keep getting this error:

An exception of type 'System.Data.ConstraintException' occurred in EntityFramework.dll but was not handled in user code Additional information: The 'ZipCode' property on 'Company' could not be set to a 'null' value. You must set this property to a non-null value of type 'System.Int32'.

Can anyone think of any reason why this would be doing that?? I've checked and double checked my database project and my local database, and they both match. And all of my unit tests pass, so I'm pretty much at a loss here.

Any help would be appreciated!


Solution

  • Your property in C# Entity Framework is apparently:

    public int ZipCode;
    

    You'll have to change that to

    public Nullable<int> ZipCode;
    

    You can also do that in the properties window in the visual editor of the entity framework's edmx file.

    UPDATE:

    It would also be advisable(if possible) to change the type of the ZipCode to string. It would not only take care of the current 'nullable' problem but would also scale very well with any change in requirements further down the line!!