Last post Nov 27, 2014 02:45 AM by Lokesh B R
Nov 27, 2014 02:29 AM|Kaesebrot|LINK
Hi I have a simple method which works with LINQ to SQL and a Custom DataContext. The purpose is simple it is supposed to create a new user database entry:
public static void CreateUser(string _userName, string _pw, string _country, string _email, string _sex, DateTime _birthDate)
using (CookBookDataContext ctx = new CookBookDataContext(Resources.ResourceFile.DBConnection))
User newUser = new Benutzer();
newUser.UserName = _userName;
newUser.Password = _pw;
newUser.Country = !string.IsNullOrEmpty(_country) ? _country : string.Empty;
newUser.EMail = _email;
newUser.Sex = !string.IsNullOrEmpty(_sex) ? _sex : string.Empty;
newUser.BirthDate = !(_birthDate == null) ? _birthDate : (DateTime?)DBNull.Value; //Exception uccurs here.
Unfortunately I get the following exception while checking if the incoming DateTime value is null:
The type of the conditional expression can not be determined because there is no implicit conversion between 'System.Datetime' and 'System.DBNull'.
After a little research I found out that I had to cast System.DBNull to nullable DateTime, at least I thought so.
newUser.BirthDate = !(_birthDate == null) ? _birthDate : (DateTime?)DBNull.Value;
Now I get another error:
Cannot cast DBNull.Value to type 'System.DateTime'.
I also tried:
newUser.BirthDate = !(_birthDate == null) ? (DateTime?)_birthDate : DBNull.Value;
because DateTime is not nullable, right? Still getting exception.
Could somebody pls help me to clarify this issue?
Nov 27, 2014 02:45 AM|Lokesh B R|LINK
1. You should make the BirthDate in database as Nullable column
2. Pass DateTime.MinValue if the _birthdate is NULL