ronlut
ronlut

Reputation: 592

Inserting an entity through Entity Framework to a table having default value column

A simple situation, but can't think of a simple solution.
I have a table in my MSSQL DB (simplified):
tbUsers

[ID] [int] IDENTITY(1,1) NOT NULL,
[FirstName] [nvarchar](25) NOT NULL,
[DateCreated] [datetime2](7) NOT NULL default GETDATE()

And I have an Entity Framework Model generated from database, that created a User POCO class for me.
What I want to achieve is that when using my database context like this

db.Users.Add(new User { Name = "Rony" });  
db.SaveChanges();

It will create a row having DateCreated set to current's date & time. What happens now is that when the User object created, the DateCreated property defaults to DateTime.MinValue and then the row in the db have this value as well.

I guess that the query executed is:

INSERT INTO dbo.tbUsers
       ([Name]
       ,[DateCreated])
VALUES
       (''
       ,'0001-01-01 00:00:00.0000000')

But should be:

INSERT INTO dbo.tbUsers
       ([Name])
VALUES
       ('')

Any help on achieving this would be appreciated.

Upvotes: 3

Views: 951

Answers (1)

George Johnston
George Johnston

Reputation: 32258

If your database is responsible for setting the field, annotate the property as Computed, e.g.

[DatabaseGenerated(DatabaseGeneratedOption.Computed)]

This can also be set on the property of this field in the EF Designer.

Upvotes: 2

Related Questions