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??
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.
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.
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.
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.
You can do it in your Product
entity class constructor,
public class Product{
public Product(){
CreateDate =DateTime.Now;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With