Pass the NULL value in the DateTime field in LINQ

My database table is like this

CREATE TABLE MYBUDGET.tbl_CurrentProperty
(
    [PropID]            INT             NOT NULL  IDENTITY(1,1),
    [UpdatedOn]         DATETIME        NOT NULL,
    [Amount]            MONEY           NOT NULL,
    [Remarks]           VARCHAR(100)    NOT NULL,
)
ALTER TABLE MYBUDGET.tbl_CurrentProperty ADD CONSTRAINT PK_CurrentProperty_PropID PRIMARY KEY ([PropID])
ALTER TABLE MYBUDGET.tbl_CurrentProperty ADD CONSTRAINT DF_CurrentProperty_UpdatedOn DEFAULT (DATEADD(MINUTE,30,DATEADD(HOUR, 5, GETUTCDATE()))) FOR [UpdatedOn]
ALTER TABLE MYBUDGET.tbl_CurrentProperty ADD CONSTRAINT CK_CurrentProperty_Amount CHECK([Amount] > -1)
GO

I am using LINQ to SQL. In C #, I only need to pass the [Amount] and [Remarks] fields, and the other fields should be used with the default values ​​([PropID] and [UpdateOn]).

In C #, I create a tbl_CurrentProperties object, as shown below,

tbl_CurrentProperties currentProperties = new tbl_CurrentProperties();
currentProperties.Amount = 50.00M;
currentProperties.Remarks = "remarks";

and then pass the object to the data context. But here Linq assigned '1/1/0001 12:00:00 AM'UpdateOn to the field. But this violates the SQL datetime range 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PMand the appearance of an exception. In addition, I cannot manually assign a NULL value to a field DateTime, since its type is null. In any case, I need to do this in order to use its default restriction. How to do it?


PS: , , . , DateTime.Now, , . SQL.

+5
3

. .

dbml UpdatedOn :

Auto Generated Value = True 
Nullable = False

, INSERT, SQL Server Profiler, SQL, , UpdatedOn INSERT. . : SQL Server , INSERT. Nullable = True UpdatedOn, LINQ to SQL INSERT .

FYI, INSERT SELECT, LINQ to SQL , .

+7

dbml "Auto Generated Value" = true .

+3

I recommend that you open the file DBMLwith XML Editorand change this column type from DateTimeto DateTime?by allowing null. Save it and the code will be created for you.

Whenever the LINQ to SQLwrong one is generated DBML, it is best to edit it yourself.

+2
source

All Articles