tags:

views:

153

answers:

3

I have a custom DataContext with a Table member...

Entry is defined as...

[Table(Name="Entry")]
public class Entry
{
  [Column]
  public DateTime MyDate { get; set; }
}

The MyDate field in the Entry table can be NULL.

I have a very simple Linq query that retrieves all records in Entry but when it encounters a NULL MyDate field, I receive a System.InvalidOperationException error with the following details...

The null value cannot be assigned to a member with type System.DateTime which is a non-nullable value type.

Is there a way to set a default DateTime (with 0 ticks, for instance) when I encounter a NULL...?

+2  A: 

If date is NULL in database, you shouldn't replace it with 0 in application. When you write 0 back to db, it will propably fail or just change value to invalid.

You can replace DateTime with DateTime?:

[Table(Name="Entry")]
public class Entry
{
[Column]
public DateTime? MyDate { get; set; }
} 

Adding ? makes property Nullable. Since it can be nullable in database, it should be nullable in your model.

LukLed
+2  A: 

My preferred approach is a nullable DateTime in this case:

[Column]
public DateTime? MyDate { get; set; }

Or:

public Nullable<DateTime> MyDate { get; set; }

Is that not an option?

Nick Craver
A: 

Can you declare it as public DateTime? MyDate { get; set; }?

If you don't want it to actually ever be null, you can do this:

private DateTime _MyDate;
public DateTime? MyDate
{
    get { return _MyDate; }
    set { _MyDate = value.GetValueOrDefault(); }
}

This will give you 0 Ticks whenever the value in the DB is NULL.

Gabe
Using this kind of property is really bad practice. You save data back to database and get error. And it also doesn't make much sense because, if you decide to use 0, you don't have to define it as DateTime? anymore.
LukLed
The question was "Is there a way to set a default DateTime (with 0 ticks, for instance) when I encounter a NULL?" This is the answer to that question. It's quite possible that he's not writing this object back to the DB and is trying to pass it to other objects that don't accept nulls.
Gabe
@gabe: So you answered ang got downvote, sorry. It wasn't me. I never gave any downvote on Stackoverflow:) You can check of my page. You answered question, but question was result of bad approach and when some decides to use your solution, he is propably not aware of consequences. I wrote about them.
LukLed