Reputation: 584
I am building an Windows Phone 8 app that uses a local database. This all works fine, but I have a TimeSpan
value which I would like to save in the database. But the app crashes when it tries to create the database with the following code:
private TimeSpan _startTime;
[Column]
public TimeSpan StartTime
{
get { return _startTime; }
set
{
if (_startTime != value)
{
NotifyPropertyChanging("StartTime");
_startTime = value;
NotifyPropertyChanged("StartTime");
}
}
}
So I changed the second line to [Column(DbType = "DATETIME")]
which works fine. But this is not what I want. Now it stores a DATETIME
while I only want to store the time. Does anyone know how to accomplish this?
The error (in Dutch):
A first chance exception of type 'System.Data.SqlServerCe.SqlCeException' occurred in Microsoft.Phone.Data.Internal.ni.dll
System.Data.SqlServerCe.SqlCeException: Het opgegeven gegevenstype is ongeldig. [ Data type (if known) = TIME ]
at System.Data.SqlServerCe.SqlCeCommand.ProcessResults(Int32 hr)
at System.Data.SqlServerCe.SqlCeCommand.CompileQueryPlan()
at System.Data.SqlServerCe.SqlCeCommand.ExecuteCommand(CommandBehavior behavior, String method, ResultSetOptions options)
at System.Data.SqlServerCe.SqlCeCommand.ExecuteNonQuery()
at System.Data.Linq.SqlClient.SqlProvider.ExecuteCommand(String command)
at System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.CreateDatabase()
at System.Data.Linq.DataContext.CreateDatabase()
at MyWPApp.Controller..ctor()
Upvotes: 0
Views: 247
Reputation: 156998
The solution proposed here is to convert the TimeSpan
yourself into a datetime
object or varchar
. Personally I would recommend to save it as a numeric type, like integer, use the seconds for example as the unit of measurement.
You could do something like this to do the conversion without effort. The StartTime
is saved to the DB, while you can use StartTimeTS
in your software:
[Column]
public int StartTime
{
get
{
return this.StartTimeTS.TotalSeconds;
}
set
{
this.StartTimeTS = new TimeSpan(0, 0, value);
}
}
private TimeSpan _startTime;
public TimeSpan StartTimeTS
{
get { return _startTime; }
set
{
if (_startTime != value)
{
NotifyPropertyChanging("StartTime");
_startTime = value;
NotifyPropertyChanged("StartTime");
}
}
}
Also, does your datatype in .NET really need to be TimeSpan
and not just DateTime
? The name seems to suggest that.
Upvotes: 3