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?

本小妞迷上赌 提交于 2019-12-23 19:31:56

问题


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!


回答1:


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!!




回答2:


you can use as

public int? ZipCode;

it means Nullable



来源:https://stackoverflow.com/questions/24192830/my-sql-table-is-set-to-allow-null-for-this-column-but-when-i-run-it-it-says-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!