Sometimes when I use LINQ to SQL I get a message error saying; "The type can't be converted to nullable value".
Does anybody knows the reason?
thanks.
Consider the following example, table/field:
Customer.CustomerId (int)
Customer.Code (int)
Consider the another table/field:
Sale.CustomerId (nullable<int>)
The field Sale.CustomerId references the field Customer.CustomerId. But the Sale.CustomerId field is nullable. If your LINQ shows like this: Sale.Customer.Code, the Code field can generate a nullable integer value, throwing an error, because in the Sale table the Customer is optional. The Customer anonymous type expecteds an integer value, but in this moment, the value is nullable. For safety, type the field Sale.Customer.Code as int? (nullable integer). Change:
Code = Sale.Customer.Code
to (int?)
Code = (int?)Sale.Customer.Code
And try again!
the column in sql is not nullable and you are passing in a value that can be null.
for example passing
DateTime? createdon
to a table the requires a createdon datetime.
some times you want to assign a Nullable values (like int? Or Nullable<int> and etc.) into not null values (like int).
To avoid of this exception you must cast your object to Nullable value before assign any value to it.like the below code:
int a = 1; //a is int and not null value
int? b = 2; //b is nullable int
a = b; //with this line code you will see compile error
a = b.value; //this is the correct syntax
I use a created query to return a row of values from a key, I have checked on the query executor but when running the program it is returning null. Please help me I'm starting to lose my mind.
I've tried debugging but the problem is coming from the fill data query and it is returning null.
// Add ref. to the Dataset
ViewMedia viewMediaSetInstance = new ViewMedia();
// Create an empty Table
ViewMedia.ViewMediaDataTable viewMediaTable = new ViewMedia.ViewMediaDataTable();
// Create the Adapter we are going to use to populate the Table
Model.ViewMediaTableAdapters.ViewMediaTableAdapter MediaTableAdapter = new Model.ViewMediaTableAdapters.ViewMediaTableAdapter();
//Use query
MediaTableAdapter.findByPublishYear(viewMediaTable, publishYear);
//It doesn't find the row
//I don't seem to find a solution even when the query returns the values in the executer.
//viewMediaTable.Rows.Count == null so doesn't get inside
if (viewMediaTable.Rows.Count > 0)
{
DataRow selectedUser = viewMediaTable.Rows[0];
media = new Media(Int32.Parse(selectedUser["MediaID"].ToString()), selectedUser["Title"].ToString(), Int32.Parse(selectedUser["PublishYear"].ToString()));
return media;
}
else
{
return null;
}
I'm expecting to return the row of data to display in a book display.
This is wonky; you've got strongly typed data rows with proper typed properties for everything, yet you're treating them as generic datarows with string column names, holding objects that you're tostring()ing and parsing. It was never intended to be used this way.
Your code should look more like this:
ViewMedia viewMediaSetInstance = new ViewMedia();
ViewMedia.ViewMediaDataTable viewMediaTable = new ViewMedia.ViewMediaDataTable();
Model.ViewMediaTableAdapters.ViewMediaTableAdapter MediaTableAdapter = new Model.ViewMediaTableAdapters.ViewMediaTableAdapter();
MediaTableAdapter.findByPublishYear(viewMediaTable, publishYear);
//don't need to access the .Rows property to get the count
if (viewMediaTable.Count > 0)
{
//don't need to access the .Rows property to get the data
ViewMediaRow selectedUser = viewMediaTable[0];
media = new Media(selectedUser.MediaID, selectedUser.Title, selectedUser.PublishYear);
return media;
}
else
{
return null;
}
I also disagree with your assertion in the code comments that datatable.Rows.Count is null. A datatable's .Count property is an integer regardless of whether a strongly or weakly typed datatable is in use; it can never be null
You don't need to create a dataset, if you enable creating a method that returns a datatable. Typically these methods are called GetDataByXXX and the fill methods are called FillByXXX (you've called your fill method findByPublishYear). It's configured on the following screen of the TA wizard:
image courtesy of nullskull.com
This can simplify your code to just the following (add a reference to Model.ViewMediaTableAdapters):
var mDT = new ViewMediaTableAdapter().GetDataByPublishYear(publishYear);
Media m = null;
if (mDT.Count > 0)
media = new Media(mDT[0].MediaID, mDT[0].Title, mDT[0].PublishYear);
return m;
Most critically here, DON'T access the first row via the .Rows collection (viewMediaDataTable.Rows[0]) because that returns a base type DataRow. Access it directly via the default property indexer on the strongly typed datatable (viewMediaDataTable[0]) as this will return an object of type ViewMediaRow which in turn has nicely named, typed properties for all the columns in the datatable
viewMediaDataTable[0].PublishYear; //ViewMediaRow is a strongly typed class that has this property as an int
viewMediaDataTable.Rows[0].PublishYear; //"DataRow does not contain a definition for 'PublishYear'"
Now, if any of the data items in the row is null and the setting of the column upon null is "throw exception" you will see an exception of type StrongTypingException- it happens when you have some column that is of a type that cannot be null (such as an int) but it's null because the database query didn't return a value for that row. You were hitting this with your code because som int column (for example) was DBNull.Value and the only thing a datarow will do whn you try to access an int column tha tis DBNull, is throw an exception. By specifying SELECT * in the query, you caused the query to return a value for the column; by not selecting a column the datatable will always treat it as null. You can still also encounter a strongtypingexception if the value of the data in the database is also null. In these cases, use the IsXXXNull() methods to determine if the property is null before trying to access it (causing a strongtypingexception)
Edit: Found the error, I was supposed to get all the columns from the query (using *) and then in the code take what I need otherwise null values get returned.
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've got a datatable with 5 columns, where a row is being filled with data then saved to the database via a transaction.
While saving, an error is returned:
The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value
It implies, as read, that my datatable has a type of DateTime2 and my database a DateTime; that is wrong.
The date column is set to a DateTime like this:
new DataColumn("myDate", Type.GetType("System.DateTime"))
Question
Can this be solved in code or does something have to be changed on a database level?
Short Answer
This can happen if you do not initialize a value to a DateTime field; the field does not accept NULL values, and it's a value type, so the default value of the non-nullable DateTime type will be used.
Setting the value fixed it for me!
Long Answer
The value of default(DateTime) is DateTime.MinValue (or new DateTime(1, 1, 1) or 01/01/0001), which is not a valid SQL datetime value.
The lowest valid value for SQL Server datetime is 01/01/1753 due to its use of a Gregorian calendar. SQL Server DateTime2 however supports dates starting at 01/01/0001. Entity Framework by default uses DateTime2 for representing dates, so the generated SQL is implicitly coercing the generated DateTime2 value to a DateTime value on the SQL Server-side.
Both the DATETIME and DATETIME2 map to System.DateTime in .NET - you cannot really do a "conversion", since it's really the same .NET type.
See the MSDN doc page: http://msdn.microsoft.com/en-us/library/bb675168.aspx
There are two different values for the "SqlDbType" for these two - can you specify those in your DataColumn definition?
BUT: on SQL Server, the date range supported is quite different.
DATETIME supports 1753/1/1 to "eternity" (9999/12/31), while DATETIME2 supports 0001/1/1 through eternity.
So what you really need to do is check for the year of the date - if it's before 1753, you need to change it to something AFTER 1753 in order for the DATETIME column in SQL Server to handle it.
Marc
In my SQL Server 2008 database, I had a DateTime column flagged as not nullable, but with a GetDate() function as its default value. When inserting new object using EF4, I got this error because I wasn't passing a DateTime property on my object explicitly. I expected the SQL function to handle the date for me but it did not. My solution was to send the date value from code instead of relying on the database to generate it.
obj.DateProperty = DateTime.now; // C#
for me it was because the datetime was..
01/01/0001 00:00:00
in this case you want to assign null to you EF DateTime Object... using my FirstYearRegistered code as an example
DateTime FirstYearRegistered = Convert.ToDateTime(Collection["FirstYearRegistered"]);
if (FirstYearRegistered != DateTime.MinValue)
{
vehicleData.DateFirstReg = FirstYearRegistered;
}
This one was driving me crazy. I wanted to avoid using a nullable date time (DateTime?). I didn't have the option of using SQL Server 2008's datetime2 type either
modelBuilder.Entity<MyEntity>().Property(e => e.MyDateColumn).HasColumnType("datetime2");
I eventually opted for the following:
public class MyDb : DbContext
{
public override int SaveChanges()
{
UpdateDates();
return base.SaveChanges();
}
private void UpdateDates()
{
foreach (var change in ChangeTracker.Entries<MyEntityBaseClass>())
{
var values = change.CurrentValues;
foreach (var name in values.PropertyNames)
{
var value = values[name];
if (value is DateTime)
{
var date = (DateTime)value;
if (date < SqlDateTime.MinValue.Value)
{
values[name] = SqlDateTime.MinValue.Value;
}
else if (date > SqlDateTime.MaxValue.Value)
{
values[name] = SqlDateTime.MaxValue.Value;
}
}
}
}
}
}
Sometimes EF does not know that is dealing with a computed column or a trigger. By design, those operations will set a value outside of EF after an insert.
The fix is to specify Computed in EF's edmx for that column in the StoreGeneratedPattern property.
For me it was when the column had a trigger which inserted the current date and time, see below in the third section.
Steps To Resolve
In Visual Studio open the Model Browser page then Model then Entity Types -> then
Select the entity and the date time property
Select StoreGeneratedPattern
Set to Computed
For this situation other answers are workarounds, for the purpose of the column is to have a time/date specified when the record was created, and that is SQL's job to execute a trigger to add the correct time. Such as this SQL trigger:
DEFAULT (GETDATE()) FOR [DateCreated].
I ran into this and added the following to my datetime property:
[Column(TypeName = "datetime2")]
public DateTime? NullableDateTimePropUtc { get; set; }
If we dont pass a date time to date time field the default date {1/1/0001 12:00:00 AM} will be passed.
But this date is not compatible with entity frame work so it will throw
conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value
Just default DateTime.now to the date field if you are not passing any date .
movie.DateAdded = System.DateTime.Now
The easiest thing would be to change your database to use datetime2 instead of datetime. The compatibility works nicely, and you won't get your errors.
You'll still want to do a bunch of testing...
The error is probably because you're trying to set a date to year 0 or something - but it all depends on where you have control to change stuff.
I found this post trying to figure why I kept getting the following error which is explained by the other answers.
The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.
Use a nullable DateTime object.
public DateTime? PurchaseDate { get; set; }
If you are using entity framework
Set the nullable property in the edmx file to True
As andyuk has already pointed-out, this can happen when a NULL value is assigned to a non nullable DateTime field. Consider changing DateTime to DateTime? or Nullable<DateTime>. Bear in mind that, in case you are using a Dependency Property, should also make sure that your dependency property's type is also a nullable DateTime type.
Below is a real life example of an incomplete DateTime to DateTime? type adjustment that raises the odd behaviour
The Entity Framework 4 works with the datetime2 data type so in db the corresponding field must be datetime2 for SQL Server 2008.
To achive the solution there are two ways.
To use the datetime data type in Entity Framwork 4 you have to switch the ProviderManifestToken in the edmx-file to "2005".
If you set corresponding field as Allow Null (it converts it to NULLABLE) so then EF automatically uses date objects as datetime.
Add the below mentioned attribute on the property in your model class.
Attribute = [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
Reference = System.ComponentModel.DataAnnotations.Schema
Initially I forgot to add this attribute. So in my database the constraint was created like
ALTER TABLE [dbo].[TableName] ADD DEFAULT (getdate()) FOR [ColumnName]
and I added this attribute and updated my db then it got changed into
ALTER TABLE [dbo].[TableName] ADD CONSTRAINT [DF_dbo.TableName_ColumnName] DEFAULT (getdate()) FOR [ColumnName]
Created a base class based on #sky-dev implementation. So this can be easily applied to multiple contexts, and entities.
public abstract class BaseDbContext<TEntity> : DbContext where TEntity : class
{
public BaseDbContext(string connectionString)
: base(connectionString)
{
}
public override int SaveChanges()
{
UpdateDates();
return base.SaveChanges();
}
private void UpdateDates()
{
foreach (var change in ChangeTracker.Entries<TEntity>())
{
var values = change.CurrentValues;
foreach (var name in values.PropertyNames)
{
var value = values[name];
if (value is DateTime)
{
var date = (DateTime)value;
if (date < SqlDateTime.MinValue.Value)
{
values[name] = SqlDateTime.MinValue.Value;
}
else if (date > SqlDateTime.MaxValue.Value)
{
values[name] = SqlDateTime.MaxValue.Value;
}
}
}
}
}
}
Usage:
public class MyContext: BaseDbContext<MyEntities>
{
/// <summary>
/// Initializes a new instance of the <see cref="MyContext"/> class.
/// </summary>
public MyContext()
: base("name=MyConnectionString")
{
}
/// <summary>
/// Initializes a new instance of the <see cref="MyContext"/> class.
/// </summary>
/// <param name="connectionString">The connection string.</param>
public MyContext(string connectionString)
: base(connectionString)
{
}
//DBcontext class body here (methods, overrides, etc.)
}
I ran into this issue on a simple console app project and my quick solution is to convert any possible datetime2 dates to a nullable datetime by running this method:
static DateTime? ParseDateTime2(DateTime? date)
{
if (date == null || date.ToString() == "1/1/0001 12:00:00 AM")
{
return null;
}
else
{
return date;
}
}
This is certainly not a completely comprehensive method, but it worked for my needs and maybe it'll help others!
In my case, when a NULL value is explicitly assigned for Nullable DateTime column and then you try to save the changes. This error will pop up.
In my case we were casting a Date to a Datetime and we got this error.
What happens is that Date has a "more programmer oriented" minimum of 01/01/0001, while Datetime is stuck at 1753
Combine that with a data collection error on our part, and you get your exception!
Sometimes it works fine on development machines and not in servers. In my case I had to put :
<globalization uiCulture="es" culture="es-CO" />
In the web.config file.
The timezone in the machine (Server) was right (to the CO locale) but the web app did not. This setting done and it worked fine again.
Off course, all dates had value.
:D
Adding this code to a class in ASP.NET worked fort me:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Properties<DateTime>().Configure(c => c.HasColumnType("datetime2"));
}
I'm aware of this problem and you all should be too:
https://en.wikipedia.org/wiki/Year_2038_problem
In SQL a new field type was created to avoid this problem (datetime2).
This 'Date' field type has the same range values as a DateTime .Net class. It will solve all your problems, so I think the best way of solving it is changing your database column type (it won't affect your table data).
Check out the following two:
1) This field has no NULL value. For example:
public DateTime MyDate { get; set; }
Replace to:
public DateTime MyDate { get; set; }=DateTime.Now;
2) New the database again. For example:
db=new MyDb();
Problem with inherited datetime attribute
This error message is often showed when a non-nullable date field has value null at insert/update time. One cause can be inheritance.
If your date is inherit from a base-class and you don't make a mapping EF will not read it's value.
For more information:
https://weblogs.asp.net/manavi/inheritance-mapping-strategies-with-entity-framework-code-first-ctp5-part-3-table-per-concrete-type-tpc-and-choosing-strategy-guidelines
I saw this error when I wanted to edit a page usnig ASP.Net MVC. I had no problem while Creating but Updating Database made my DateCreated property out of range!
When you don't want your DateTime Property be Nullable and do not want to check if its value is in the sql DateTime range (and #Html.HiddenFor doesn't help!), simply add a static DateTime field inside related class (Controller) and give it the value when GET is operating then use it when POST is doing it's job:
public class PagesController : Controller
{
static DateTime dateTimeField;
UnitOfWork db = new UnitOfWork();
// GET:
public ActionResult Edit(int? id)
{
Page page = db.pageRepository.GetById(id);
dateTimeField = page.DateCreated;
return View(page);
}
// POST:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Page page)
{
page.DateCreated = dateTimeField;
db.pageRepository.Update(page);
db.Save();
return RedirectToAction("Index");
}
}
Check the req format in DB. eg my DB have Default value or Binding (((1)/(1))/(1900))
System.DateTime MyDate = new System.DateTime( 1900 ,1, 1);
For me I have had a Devexpress DateEdit component, which was binded to nullable datetime MSSQL column thru the Nullable model property. All I had to do was setting AllowNullInput = True on DateEdit. Having it "Default" caused that the date 1.1.0001 appeared - ONLY BEFORE leaving the DateEdit - and then I got this conversion error message because of subsequent instructions mentioned above.
you will have date column which was set to lesathan the min value of allowed dattime like 1/1/1001.
to overcome this issue you can set the proper datetime value to ur property adn also set another magical property like IsSpecified=true.
For Code First Context:
Go from this
public DateTime Created { get; set; }
To this. Add the [DatabaseGenerated(DatabaseGeneratedOption.Computed)] attribute.
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime Created { get; set; }
in your model.
Be sure to add this to the top as well
using System.ComponentModel.DataAnnotations.Schema;