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...?
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.
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?
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.
精彩评论