Cannot convert from 'System.DateTime' to 'System.Data.Linq.Binary' error - c#

In the program I'm currently working on, my table has a Create_Timestamp column, which I defined as timestamp.
When I'm working with my data context and my form values in my controller on the HttpPost, I'm trying the following:
NewsArticle article = new NewsArticle();
article.Create_Timestamp = System.DateTime.Now;
The error I get is Cannot implicitly convert from 'System.DateTime' to 'System.Data.Linq.Binary'
I've tried to force the conversion, but I'm unsure exactly what I'm doing at this point.
Is it possible in C# to do this conversion and still have Linq be happy with me?
Thanks

I am guessing you are using the SQL timestamp type in your table and you are expecting it to be a DateTime. Timestamp isn't really meant for holding Date/Time information. From MSDN (http://msdn.microsoft.com/en-us/library/aa260631(SQL.80).aspx):
timestamp is a data type that exposes
automatically generated binary
numbers, which are guaranteed to be
unique within a database. timestamp is
used typically as a mechanism for
version-stamping table rows. The
storage size is 8 bytes.storage size is 8 bytes.
Change your column "Create_Timestamp" to DateTime and you should be fine.

Related

InvalidCastException when using datareader.getString() on a string field that contains numerical value

I have a field in a sqlite database, we'll call it field1, on which I'm trying to iterate over each record (there's over a thousand records). The field type is string. The value of field1 in the first four rows are as follows:
DEPARTMENT
09:40:24
PARAM
350297
Here is some simple code I use to iterate over each row and display the value:
while (sqlite_datareader.Read())
{
strVal = sqlite_datareader.GetString(0);
Console.WriteLine(strVal);
}
The first 3 values display correctly. However, when it gets to the numerical entry 350297 it errors out with the following exception on the .getString() method
An unhandled exception of type 'System.InvalidCastException' occurred in System.Data.SQLite.dll
I've tried casting to a string, and a bunch of other stuff. But I can't get to the bottom of why this is happening. For now, I'm forced to use getValue, which is of type object, then convert back to a string. But I'd like to figure out why getString() isn't working here.
Any ideas?
EDIT: Here's how I currently deal with the problem:
object objVal; // This is declared before the loop starts...
objVal = sqlite_datareader.IsDBNull(i) ? "" : sqlite_datareader.GetValue(i);
if (objVal != "")
{
strVal = (string)objVal;
}
What the question should have included is
The table schema, preferrably the CREATE TABLE statement used to define the table.
The SQL statement used in opening the sqlite_datareader.
Any time you're dealing with data type issues from a database, it is prudent to include such information. Otherwise there is much unnecessary guessing and floundering (as apparent in the comments), when so very useful, crucial information is explicitly defined in the schema DDL. The underlying query for getting the data is perhaps less critical, but it could very well be part of the issue if there are CAST statements and/or other expressions that might be affecting the returned types. If I were debugging the issue on my own system, these are the first thing I would have checked!
The comments contain good discussion, but a best solution will come with understanding how sqlite handles data types straight from the official docs. The key takeaway is that sqlite defines type affinities on a column and then stores actual values according to a limited set of storage classes. A type affinity is a type to which data will attempt to be converted before storing. But (from the docs) ...
The important idea here is that the type is recommended, not required. Any column can still store any type of data.
But now consider...
A column with TEXT affinity stores all data using storage classes NULL, TEXT or BLOB. If numerical data is inserted into a column with TEXT affinity it is converted into text form before being stored.
So even though values of any storage class can be stored in any column, the default behavior should have been to convert any numeric values, like 350297, as a string before storing the value... if the column was properly declared as a TEXT type.
But if you read carefully enough, you'll eventually come to the following at the end of section 3.1.1. Affinity Name Examples:
And the declared type of "STRING" has an affinity of NUMERIC, not TEXT.
So if the question details are taken literally and field1 was defined like field1 STRING, then technically it has NUMERIC affinity and so a value like 350297 would have been stored as an integer, not a string. And the behavior described in the question is precisely what one would expect when retrieving data into strictly-typed data model like System.Data.SQLite.
It is very easy to cuss at such an unintuitive design decisions and I won't defend the behavior, but
at least the results of "STRING" type are clearly stated so that the column can be redefined to TEXT in order to fix the problem, and
"STRING" is actually not a standard SQL data type. SQL strings are instead defined with TEXT, NTEXT, CHAR, NCHAR, VARCHAR, NVARCHAR, etc.
The solution is either to use code as currently implemented: Get all values as objects and then convert to string values... which should be universally possible with .Net objects since they should all have ToString() method defined.
Or, redefine the column to have TEXT affinity like
CREATE TABLE myTable (
...
field1 TEXT,
...
)
Exactly how to redefine an existing column filled with data is another question altogether. However, at least when doing the conversion from the original to the new column, remember to use a CAST(field1 AS TEXT) to ensure the storage class is changed for the existing data. (I'm not certain whether type affinity is "enforced" when simply copying/inserting data from an existing table into another or if the original storage class is preserved by default. That's why I suggest the cast to force it to a text value.)

Which data type holds Oracle sdo_Geometry data type in C#

in Oracle Database, I have got a table which contains as a number, varchar etc variables. in addition, it has sdo_geometry object column. the task I have wanted, I would like to fetch this sdo_geometry data type and assign inside appropriate data type using c#. I will be happy if you solve this issue.
Thanks for now
Best Regards...
I don't know if there's a .NET type you can map directly to that, but you can call Get_WKT to get the well known text.
SELECT ID, Name, myPolygon.Get_WKT() FROM YourSource
You can read that into a SqlGeometry object at run time if you need.

Timestamp column in sql to valid string representation

I have a table with Column data type "timestamp" in sql server.
Currently I am trying to get the data from this table to sqlite database. as it needs only string value. So far i have not been able to find correct way to convert to string.
So for example my SQL Value is 0x0000000000012DE0
When I get the record using entity framework, I get byte array.
Tried to convert using following code to string.
value = BitConverter.ToInt64(Version, 0);
However for same record, i get 0xE02D010000000000
This is one difference.
The second, Since I am working on azure mobile app, and this data also goes to android via WebAPI controller.The result I get from fiddler is something in this format
AAAAAAABM8s=
I want to also convert the byte arrray value in above format .
Any suggestions?
I had a similar issue with my ASP.NET Core, EF Core 2.0, Angular 2 app. This was a database first development and changing the database definition was not within my remit.
In my case, EF Core automatically performed the concurrency check for me where the Timestamp column was present in the table. This was not an issue for updates because I could pass the DTO in the body but with deletes I could not.
To pass the timestamp I used a query string. The value being the Base64 string representation of the timestamp e.g. AAAAAAACIvw=
In my repository layer I convert the string back to a byte array e.g.
byte[] ts = Convert.FromBase64String(timestampAsBase64String);
Then delete using the create and attach pattern (thereby eliminating any chance of lost updates)
ModelClass modelobj = new ModelClass { Id = id, Timestamp = ts};
_dbcontext.Entry(modelObj).State = EntityState.Deleted;
Thanks to this thread and the CodeProject article Converting Hexadecimal String to/from Byte Array in C# to get this resolved.

Database datatype Conversion Issue

I am fetching data from sql server and exporting it to excel programmatically using c#.Based on the column data type, I am doing format of cell.Here I am facing one issue.
In sql server,retrieving column data type is defined as numeric(20,0).In my application column type is coming as Decimal.I want to get the type other numeric type like Double or Int64. Is there any way to get it?
Since the datatype in the DB is numeric, you have two options to get either a double or int.
Change the datatype in the database from numeric to int.
Receive the data as a decimal and round it. For this, use Math.Round as Convert.ToInt32 can have some unexpected behavior.

Assign a Date variable in SSIS Script Componentt

In my script component, I am trying to assign a value to a Date column (the datatype is DT_DATE). These are DateTime objects in C#, so I thought the following would work:
FooBuffer.Datevar = DateTime.Now;
It compiles, but the line gives an error at runtime:
Error: 0xC020901C at FoobarFlow, OLE DB Destination [77]: There was an error with OLE DB Destination.Inputs[OLE DB Destination Input].Columns[Datevar] on OLE DB Destination.Inputs[OLE DB Destination Input]. The column status returned was: "The value could not be converted because of a potential loss of data.".
My guess is that, since the DateTime class in C# is designed to have precision up to seconds (or even milliseconds -- not sure), and DT_DATE's precision only goes up to days, there would be a possible loss of information.
So the question is, how do I assign such a column's value correctly? Is there any way to convert DateTime object to a Date before assigning it?
Assuming you have a DateTime value in an arbitrarily named variable newDate, try the following:
FooBuffer.DateVar = new DateTime(newDate.Year,
newDate.Month,
newDate.Day,
newDate.Hour,
newDate.Minute,
newDate.Second);
DateTime.Now contains more precision than DT_DATE is capable of storing. Try this instead.
DateTime.Now.Date

Categories