Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is EF DataBase First not use getdate()?

I am using EF 4.1 with database first.

Example table:

CREATE TABLE dbo.Product(
   [ID] [int] IDENTITY(1,1) not null,
   Title nvarchar(200) not null,
   CreateDate datetime not null default(getdate()),
)

When I add a new row, I get an exception about DateTime type overflow.

The getdate() of database settings is invalid.

I must be set the storeGeneatePattern property of the createdate field to Computed.

Is there any way to let the EF automatically generated the DateTime column without manually set??

like image 523
Rock_Choke Avatar asked Apr 24 '12 05:04

Rock_Choke


People also ask

How to update Entity framework model from database first?

Right-click anywhere on the design surface, and select Update Model from Database. In the Update Wizard, select the Refresh tab and then select Tables > dbo > Student. Click Finish.

What is Entity framework database first?

Database First allows you to reverse engineer a model from an existing database. The model is stored in an EDMX file (. edmx extension) and can be viewed and edited in the Entity Framework Designer. The classes that you interact with in your application are automatically generated from the EDMX file.

What is EDMX in Entity framework?

edmx file is an XML file that defines a conceptual model , a storage model , and the mapping between these models. An . edmx file also contains information that is used by the ADO.NET Entity Data Model Designer (Entity Designer) to render a model graphically.


2 Answers

No EF will never use your database default. The reason is that your entity has non nullable DateTime property. This property has by default assigned default value in .NET which is 1.1.0001. EF doesn't know if you assigned that value or if it is default value so it always explicitly passes this value to the database. Same happens if you use nullable type but in this case EF will pass explicitly null. In both cases default value from database will not be applied because that value is applied only when the value from application is not explicitly passed in an insert command - EF explicitly passes all values from entity.

like image 56
Ladislav Mrnka Avatar answered Nov 15 '22 04:11

Ladislav Mrnka


You can do it in your Product entity class constructor,

public class Product{
  public Product(){
     CreateDate =DateTime.Now;
  }
}
like image 23
Jayantha Lal Sirisena Avatar answered Nov 15 '22 06:11

Jayantha Lal Sirisena