Entity framework generates values for NOT NULL columns which has default defined in db.
Posted
by
Muhammad Kashif Nadeem
on Stack Overflow
See other posts from Stack Overflow
or by Muhammad Kashif Nadeem
Published on 2011-03-17T15:27:52Z
Indexed on
2011/03/17
16:10 UTC
Read the original article
Hit count: 248
c#
|entity-framework-4
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 = "[email protected]";
// 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='[email protected]',@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.
© Stack Overflow or respective owner