I'm trying to insert record using C# and SQL, but i got this error when date column is empty, i searched for a similar cases but didnt solve it yet. It inserts 01/01/1900, the column in table is Datetime any idea or similar case link.
[HttpPost]
public HttpResponseMessage save (Education edu)
{
Dictionary<string, object> xmt = new Dictionary<string, object>();
xmt.Add("#Staff_Key", edu.Staff_Key);
xmt.Add("#Type_Education", edu.Type_Education);
xmt.Add("#Qual", edu.Qual);
xmt.Add("#Uni", edu.Uni);
xmt.Add("#Date_Issue", edu.Date_Issue.ToString() == null ? "Null" : edu.Date_Issue.ToString());
xmt.Add("#Notes", edu.Notes);
obj.ExecNonQuery(
#"insert into HR_DocEducation (Staff_Key,Type_Education,Qual,Uni,Date_Issue,Notes)
values (#Staff_Key,#Type_Education,#Qual,#Uni,#Date_Issue,#Notes) ",xmt);
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created);
return response;
Hassan,
I had the same issue, the trick in addition to use the nullable DateTime DateTime? object is correcting the ternary operator as follows:
xmt.Add("#Date_Issue", edu.Date_Issue == null ? (object) DBNull.Value : (object)edu.Date_Issue);
instead of
xmt.Add("#Date_Issue", edu.Date_Issue.ToString() == null ? "Null" : edu.Date_Issue.ToString());
As said by Astha Srivastava, you can find a short description of DateTime's behavior on null values.
Question: DateTime “null” value
A possible way is to use the propertie DBNull.Value which is referencing to a value used on databases. I can recommend to use that when using SQL Commands.
After a short lookup I found a similar question of yours, using the DBNull.Value as example. Look it up and if it might help you give the answer a upvote.
Question: Nullable DateTime and the Database
Related
I query some field from database, the Planstartdate is datetime type, and the Planstartdate can be null, I want to format the Planstartdate to "yyyy-MM-dd"
DataTable dt = ds.Tables[0];
var query = dt.AsEnumerable()
.Select(dr =>
new InitOverview
{
IID = string.IsNullOrEmpty(dr.Field<string>("IID").ToString()) ? "" : dr.Field<string>("IID"),
ProjectName = string.IsNullOrEmpty(dr.Field<string>("ProjectName")) ? "" : dr.Field<string>("ProjectName"),
TeamLead = string.IsNullOrEmpty(dr.Field<string>("TeamLead")) ? "" : dr.Field<string>("TeamLead"),
Status = string.IsNullOrEmpty(dr.Field<string>("Status")) ? "" : dr.Field<string>("Status"),
OverallStatus = string.IsNullOrEmpty(dr.Field<string>("OverallStatus")) ? "" : dr.Field<string>("OverallStatus"),
Planstartdate = dr.Field<DateTime?>("Planstartdate"),
Planenddate = dr.Field<DateTime?>("Planenddate"),
Actualstartdate = dr.Field<DateTime?>("Actualstartdate"),
Actualenddate = dr.Field<DateTime?>("Actualenddate")
}
).ToList();
anybody can help to realize it?
Thanks
Assuming you have a nullable DateTime stored in a variable, you need to check whether it's null or not. Then you can access the underlying value and convert it to a string. Nullable types provide a boolean property HasValue that you should check prior to trying to work with the underlying object.
using System;
public class Program
{
public static void Main()
{
DateTime? actualStartDate = DateTime.Now;
if(actualStartDate.HasValue)
{
string s = actualStartDate.Value.ToString("yyyy-MM-dd");
Console.WriteLine("value: " + s);
}
}
}
Fiddle here.
If you want to do this within your object initializer, it would look something like this, using a ternary operator:
new InitOverview
{
Planstartdate = dr.Field<DateTime?>("Planstartdate").HasValue
? dr.Field<DateTime?>("Planstartdate").Value.ToString("yyyy-MM-dd") : "no date";
}
Fiddle here.
However, I would caution you that converting it to a string at this point is probably not a good idea. In code, you should generally leave dates as dates until they actually need to be displayed to a user, so you delay it as long as possible. Only in the view layer of your application should you actually convert a date to a string. This keeps the API cleaner (no need to convert it to a date again to manipulate it) and ensures that it's simple to convert to the correct format for display to the user according to their culture settings.
Also, you're doing boring wiring up of database records to .NET objects. It's tedious and a waste of time. You should use a micro ORM such as Dapper and make this much cleaner. It could be:
using (var connection = new SqlConnection(connectionString))
{
return connection.Query<InitOverview>(selectStatement).AsList();
}
While #mason's answer definitely works, I would like to add that since you are using DataTable, there might be the case that you are fetching dates from Database (and convert it to datatable to print in excel or vice versa), in such case 'HasValue' might not work if database contains DBNull.Value. Therefore, you should also check if the data you are fetching has DBNull.Value or not.
new InitOverview
{
Planstartdate = dr["PlantStartDate"]!=DBNull.Value ? "Check Null condition mentioned in previous answer" : "no date";
}
I have to do a c# search on records in an array from a sql server db
using 3 data elements. One of the data elements has to be a DateTime element in a column called DateOfBirth. Unfortunately there are a lot of null values in this column and I can't figure out how to compare a DateTime variable to a field with NULL values. I see a lot of answers that appear to be close to what I need here, but nothing has helped. Thanks for any help, This has been my format.
if ((DateTime)dt == (DateTime)temp[i].Individual.DateOfBirth)
GlobalNum3.bnum3 = 1;
I'm assuming that dt is already a DateTime, in which case it can't be null (DateTime is a struct) and there's no need to cast it.In addition, either temp[i].Individual.DateOfBirth is a DateTime too and so cannot be null either, or it's a Nullable<DateTime>.
Assuming both are DateTimes, DB nulls will be set to DateTime.MinValue, so just compare the values:
if (dt == (DateTime)temp[i].Individual.DateOfBirth)
{
GlobalNum3.bnum3 = 1;
}
However, if temp[i].Individual.DateOfBirth is a Nullable<DateTime>, it might be null, or might simply have no value, so use it like this:
var possibleDateOfBirth = temp[i].Individual.DateOfBirth;
if (possibleDateOfBirth != null &&
possibleDateOfBirth.HasValue &&
dt == possibleDateOfBirth.Value)
{
GlobalNum3.bnum3 = 1;
}
If you are querying the DB then try testing the nullable .HasValue property like this:
if (temp[i].Individual.DateOfBirth.HasValue && dt == temp[i].Individual.DateOfBirth.Value)
{
GlobalNum3.bnum3 = 1;
}
Obviously I'm assuming you are testing DateTime? properties.
I would like to create a helper class to do some common task.
For example, I am retrieving some results from Database and then assigning the values to variables. But some of the fields in my records might contain null as well. I would like to check before assigning that the value does not contain any null.
Also there are some variable those are type int, so like to check before parsing to the specific type.
int iValue=int.parse(Helpers.IsNull(dr[colName].toString()));
string strValue=Helpers.IsNull(dr[colName].toString());
How should I create a helper class and what value should I return with IsNull method?
Little confuse..
Thanks
Well what you are trying to acchieve is to avoid the NullReferenceException i guess.
You could achieve this by writing a generic method like this
public static TValue GetValueSafe<TValue,TObject>(TObject obj, Func<TObject,TValue> accessor)
{
if(obj== null)
return default(TValue);
return accessor(obj);
}
Then use it like this:
string strValue = Helpers.GetValueSafe(dr[colName], o => o.toString());
This would either return the value of toString, or if dr[colName] == null returns default(string) which is null.
You could exand this by adding a defaultParameter to define a value on "failure".
However i would'nt recommend using this.
A more radical approach (which would remove the issue) would be to eradicate NULLs from your values altogether.
The simplest way would be through ISNULL() when you query your database:
Where now you do
SELECT MyColumn FROM MyTable
You instead go
SELECT ISNULL(MyColumn, '') AS MyColumn FROM MyTable
Then you can assume no NULLs will get through to your code.
I have read
What is the difference between null and System.DBNull.Value?
INSERT / UPDATE data using DBNull or null?
and similar Q&A but don't quite understand this.
The problem:
tableAdapter allow's me storing null into not nullable fields (AllowDBNull = false).
What I need to check?
I can check for
string.Lenght == 0
string.IsNullOrEmpty(string)
string.text = ""
before update command but want to know why table adapter is letting me storing NULL
it's actually storing someTextBox.Text = "" when needed to throw exception null not allowed for some field.
I have exactly same problem Dataset allowing Null values even when AllowDBNull = False? but there are no solution.
Thanks
I would need more code to see for sure what you are doing, but:
public static object GetValue(string value) {
if (!String.IsNullOrEmpty(value)) {
return value;
}
return DBNull.Value;
}
Would that solve your issues?
I'm attempting to use the DataSet designer to create a datatable from a query. I got this down just fine. The query used returns a nullable datetime column from the database. But, when it gets around to this code:
DataSet1.DataTable1DataTable table = adapter.GetData();
This throws a StrongTypingException from:
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public System.DateTime event_start_date {
get {
try {
return ((global::System.DateTime)(this[this.tableDataTable1.event_start_dateColumn]));
}
catch (global::System.InvalidCastException e) {
throw new global::System.Data.StrongTypingException("The value for column \'event_start_date\' in table \'DataTable1\' is DBNull.", e);
}
}
set {
this[this.tableDataTable1.event_start_dateColumn] = value;
}
}
How do I use the designer to allow this column to be Nullable?
Typed data sets don't support nullable types. They support nullable columns.
The typed data set generator creates non-nullable properties and related methods for handling null values. If you create a MyDate column of type DateTime and AllowDbNull set to true, the DataRow subclass will implement a non-nullable DateTime property named MyDate, a SetMyDateNull() method, and an IsMyDateNull() method. This means that if you want to use a nullable type in your code, you have to do this:
DateTime? myDateTime = myRow.IsMyDateNull() ? null : (DateTime?) row.MyDate;
While this doesn't totally defeat the purpose of using typed data sets, it really sucks. It's frustrating that typed data sets implement nullable columns in a way that's less usable than the System.Data extension methods, for instance.
Is particularly bad because typed data sets do use nullable types in some places - for instance, the Add<TableName>Row() method for the table containing the nullable DateTime column described above will take a DateTime? parameter.
Long ago, I asked about this issue on the MSDN forums, and ultimately the ADO project manager explained that nullable types were implemented at the same time as typed data sets, and his team didn't have time to fully integrate the two by .NET 2.0's ship date. And so far as I can tell, they haven't added new features to typed data sets since then.
Thanks this solved my similar issue : Here is the code.
In case of this question
Isevent_start_date()
would return whether or not the field is null.
In my case: I had a similar problem and I used the following solution
//Table's Name is Efforts,
//Column's name is Target
//So the dataset would automatically generate a property called IsTargetNull() which can be used to check nullables
//Create an Adaptor
EffortsTableAdapter ad = new EffortsTableAdapter();
ProjectDashBoard.Db.EffortsDataTable efforts = ad.GetData();
DataColumn targetColumn = new DataColumn();
targetColumn = efforts.TargetColumn;
List<DateTime?> targetTime = new List<DateTime?>();
foreach (var item in efforts)
{
//----------------------------------------------------
//This is the line that we are discussing about :
DateTime? myDateTime = item.IsTargetNull() ? null : (DateTime?)item.Target;
//----------------------------------------------------
targetTime.Add(myDateTime);
}
It seems the Designer got the Database type for the column wrong.
Open up the xsd Designer, hit F4 to get the Properties Window open. Select the appropriate column and set Nullable (or something like that, don't remember the exact name) to true.
To make this work with LINQ you will have to go to the Tables properties in your dataset.xsd. First look and make sure that the column is indeed set to nullable. THEN you must look at specific property "NullValue" for the column. Null Value defaults to "Exception", at least in VS 2012. Set it to Nothing for VB such that you can do "IsNot Nothing" in the LINQ Where clause.
I did this to insert value NULL in a DateTime column,
assuming that I have a nullable DateTime column in Database, I retrieved some data from the database in an object called response and I want to insert nullable DateTime value in the DataSet column that called RenewDate:
// create anew row of the same type of your table row
var rw = ds.StudentActionPrintDT.NewStudentActionPrintDTRow();
// check for null value
if(!response.RenewDate.HasValue)
{
// if null, then the let DataSet to set it null by it's own way
rw.SetRenewDateNull();
}
else
{
// if not null set value to the datetime value
rw.RenewDate = response.RenewDate.Value;
}
// add the created row to the dateset [DataSetName].[ColumnName].Add[ColumnName]Row([The Created Row]);
ds.StudentActionPrintDT.AddStudentActionPrintDTRow(rw);
In DataSet Designer, use System.Object data type instead of System.DateTime and set NullValue to (Null) and DefaultValue to <DBNull> and when it is needed, convert it such as:
var row1 = dateSet1.table1.FirstOrDefault();
if (row1 == null)
return;
DateTime? date = (DateTime?) row1.ObjectDate;
I am using the code listed below to handle null cells in an Excel sheet that is read in to a datatable.
if (!reader.IsDBNull(0))
{
row["DateOnCall"] = (DateTime)reader[0];
}
It seems different with DataTable and Strongly Typed DataTable... Use Like this.
DataSet1.DataTable1DataTable table = new DataSet1.DataTable1DataTable();
table.Merge(adapter.GetData().CopyToDataTable());
The System.DateTime Object is not nullable. To make a DateTime nullable make it a DateTime? (put a ? after DateTime)
DateTime? nullableDateTime = null;