问题
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??
回答1:
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.
回答2:
You can do it in your Product
entity class constructor,
public class Product{
public Product(){
CreateDate =DateTime.Now;
}
}
来源:https://stackoverflow.com/questions/10292179/why-is-ef-database-first-not-use-getdate