views:

1331

answers:

3

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.

+3  A: 

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

Andrew Hare
First you should accept null values on the appropriate database field value.
Izabela
I am using vb.net which does not have Nulls. I have to use Nothing instead which sets the date to the default value instead of Null.
@Eric VB.NET "Nothing" is C#'s "null"
splattne
A: 

I never used entity-framework but can you turn a variable into a nullable type?

something like

dim entityVar as nullable(of date)

then you can do the =nothing and it will stay nothing.

but like I said, I never used entity-framework

while looking on google I found that bug report on Microsoft Connect

Fredou
I set it to nullable in the model.designer.vb file but that still doesn't set it to null in the database. That bug report is similar to my problem. There must be a way to do this. You wouldn't think they would release entity framework without the ability to set database values to null in vb.net.
+2  A: 

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

Alex James
Yes that is correct Alex. The problem was on my side. A field which I thought was nullable was not.