Hi I have a table Customer. One of the columns in table is DateCreated. This column is NOT NULL but default values is defined for this column in db.
When I add new Customer using EF4 from my code.
var customer = new Customer();
customer.CustomerName = "Hello";
customer.Email = "hello@ello.com";
// Watch out commented out.
//customer.DateCreated = DateTime.Now;
context.AddToCustomers(customer);
context.SaveChanges();
Above code generates following query.
exec sp_executesql N'insert [dbo].[Customers]([CustomerName],
[Email], [Phone], [DateCreated], [DateUpdated])
values (@0, @1, null, @2, null)
select [CustomerId]
from [dbo].[Customers]
where @@ROWCOUNT > 0 and [CustomerId] = scope_identity()
',N'@0 varchar(100),@1 varchar(100),@2 datetime2(7)
',@0='Hello',@1='hello@ello.com',@2='0001-01-01 00:00:00'
And throws following error
The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.
The statement has been terminated.
Can you please tell me how NOT NULL columns which has default values at db level should not have values generated by EF?
DB:
DateCreated DATETIME NOT NULL
DateCreated Properties in EF:
- Nullable: False
- Getter/Setter: public
- Type: DateTime
- DefaultValue: None
Thanks.
From my knowledge of EF (which is minimal), it does not grab the default value from the schema. The fact that you are inserting the row and the column is marked as NOT NULL, means EF thinks it should be inserting a value for that column which happens to have the value of DateTime.MinValue.
You may need to force your own values in the entities constructor or create some factory methods.
Is there anything on the property pages of the table designer in EF that lets you specify a default value?