In Entity Framework, how do I set a field to DBNull?

dbnull entity-framework

Question

How do you set a field to DBNull in Entity Framework? The fields are strongly typed so you cannot set it equal to DBNull.Value and I did not find any method to set a field to DBNull. It seems like this is a necessary thing to do, but after much Google research I found nothing about it.

I am trying to set a datetime field in Entity Framework using vb.net. This requires me to write

 myEntity.mydate = Nothing

This does not set the field to null but instead sets it to the default date value which is not a valid date value in SQL Server.

1
8
5/4/2009 5:54:03 PM

Accepted Answer

If a column is nullable in the database the result class will have a nullable property too.

For example if a Order table has a nullable Datetime column called CreatedDate, then the resulting Order class will looks something like this:

public partial class Order: EntityObject
{
  ...
  private DateTime? _createdDate;
  ...
}

If the _createdDate has no value when you call ObjectContext.SaveChanges() a System.DBNull will automatically be sent to the database as part of insert or update command.

Hope this helps Alex

15
5/5/2009 8:55:59 PM

Popular Answer

Set the field value to null. The Entity Framework will translate this to System.DBNull.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow