I am developing a MVC application. I have one timestamp column in a SQL table. I have one query to retrieve all data from database. I am using LINQ.
Below is my query:
obj = (from c in entityObject.NCT_ProcessAudit.AsNoTracking()
join proc in entityObject.NCT_Process_Settings on c.process_id equals proc.ID
select new returnObject
{
ID = c.ID,
process_id = c.process_id,
icon_id = c.icon_id,
dispaly_order = c.dispaly_order,
updated = c.updated, //c. updated timestamp in sql and updated is datetime as public Nullable<System.DateTime> updated { get; set; }
output = c.output
}).OrderByDescending(a => a.updated).ToList();
When I run above query I get the following error
The specified cast from a materialized 'System.Byte[]' type to a nullable 'System.DateTime' type is not valid.
May I get some help here. Any help would be appreciated. Thank you.
As i wrote in the comments:
The SQL timesatamp type is not exactly as one might guess by its name.
It's actually just a running number that is usually used for row versioning.
In your case, by the name of the field (updated) i guess that you would like to know when was the row updated, thus, it is better for you to use datetime as the type of the field.
All of this by the way is written in MSDN:
Is a data type that exposes automatically generated, unique binary numbers within a database. timestamp is generally used as a mechanism for version-stamping table rows. The storage size is 8 bytes. The timestamp data type is just an incrementing number and does not preserve a date or a time. To record a date or time, use a datetime data type.
In recent versions of SqlServer this type was deprecated and replaced by rowversion
Related
I'm currently building a data export/import tool for pulling data into a Visual Fox Pro database from an excel or CSV document.
I believe the code to be functional, however upon execution I recieve a data type mismatch error.
After some investigation I've notice a difference between the format of the dates I'm pulling and the field I'm pushing to.
The Fox pro database is set up to take Date records, however the data i'm trying to push is in date time format (the original record is date) but as far as I'm aware c# can only natively do datetime conversion.
The code getting the date from excel is as such:
importCommand.Parameters["TENSDATE"].Value = exportReader.IsDBNull(0)
? (object) DBNull.Value
: DateTime.Parse(exportReader.GetValue(0).ToString());
Now, I've seen a lot of people use something like:
exportReader.GetValue(0).ToString("dd/MM/yyyy")
However I can't seem to get this functioning. Can someone advise me on the best way to achieve my goal.
You need to supply the type of the field when adding it to parameters. In this specific case, OdbcType.DateTime for a date field.
importCommand.Parameters.Add("#TENSDATE", OdbcType.DateTime).Value = exportReader.IsDBNull(0)
? (object) DBNull.Value
: DateTime.Parse(exportReader.GetValue(0).ToString());
If you want to parse dates which are in specific format you should use DateTime.TryParseExact method. You'll be able to pass specific format as an argument. Please refer to: https://msdn.microsoft.com/en-us/library/ms131044(v=vs.110).aspx
(Joshua Cameron-Macintosh, please close your open threads)
Despite my prior warnings, you are trying to do that the hard way, be it. VFP is a good data centric language and is clever enough to put a DateTime value into a Date or DateTime field. It is also clever enough to parse text values that denote a Date(time) - in the case of text, just like any other database or non-database parsers it does the parsing with given rules (such as using common canonical ODBC format of yyyyMMdd HH:mm:ss with no problem, or if instructed to use a format of say DMY, it knows 1/2/2000 means Feb 1st,2000 etc.). In summary here the problem is not on VFP side at all. If you use CSV, then be sure you are using ODBC canonical format for dates (same goes on with SQL Server for example). In case of Excel file, provided you have the correct data types, you can directly transfer with no additional work, particularly that DBNull trial was totally unnecessary, VFP knows DbNull.Value already.
Anyway code always talks better.
For this sample assume you have an excel file (d:\temp\ExcelImportData.xlsx) with SampleSheet sheet where you have the data columns as:
Customer ID: string
Order ID: integer
Ordered On: DateTime && where time parts were insignificant fro demo purposes
Shipped On: DateTime && Has NULL values
(You can build such a sample sheet using Northwind sample database's Orders table)
There is a VFP table (d:\temp\SampleImport.dbf) as the receiver where column information is:
CustomerId: Char(10) NOT NULL
OrderID: Int NOT NULL
OrderDate: Date NOT NULL
ShippedOn: DateTime NULL
Here is the simple read/write using a reader:
void Main()
{
var vfpConnection = #"Provider=VFPOLEDB;Data Source=D:\temp";
var xlsFileName = #"D:\temp\ExcelImportData.xlsx";
var xlsConnection = $#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={xlsFileName};" +
"Extended Properties=\"Excel 12.0;HDR=Yes\"";
var xlsTableName = "SampleSheet$";
using (var xlsCon = new OleDbConnection(xlsConnection))
using (var vfpCon = new OleDbConnection(vfpConnection))
{
var cmdInsert = new OleDbCommand(#"insert into SampleImport
(CustomerId, OrderId, OrderDate, ShippedOn)
values
(?,?,?,?)", vfpCon);
cmdInsert.Parameters.Add("customerId", OleDbType.WChar);
cmdInsert.Parameters.Add("orderId", OleDbType.Integer);
cmdInsert.Parameters.Add("orderDate", OleDbType.Date);
cmdInsert.Parameters.Add("shippedOn", OleDbType.Date);
var readXl = new OleDbCommand($"select * from [{xlsTableName}]", xlsCon);
xlsCon.Open();
vfpCon.Open();
var xlReader = readXl.ExecuteReader();
while (xlReader.Read())
{
cmdInsert.Parameters["customerId"].Value = xlReader["Customer ID"];
cmdInsert.Parameters["orderId" ].Value = xlReader["Order ID"];
cmdInsert.Parameters["orderDate" ].Value = xlReader["Ordered On"];
cmdInsert.Parameters["shippedOn" ].Value = xlReader["Shipped On"];
cmdInsert.ExecuteNonQuery();
}
xlsCon.Close();
vfpCon.Close();
}
}
I have data in IBM DB2 and what I am trying to do is to get that data using EntityFramework.
I have one column that has TIMESTAMP values in this format: dd.MM.yyyy hh:mm:ss.ffffff and it is primary key in that table.
When I am getting data from DB2 database time part of timestamp is lost.
On the other side I have entity that has string property for that Id:
public string Id { get; set; }
This is a method that will return specific merchant. It is expected only one, because timestamps aka Ids are unique. But, when data gets pulled and when time part is lost I get 9 merchants with same Id and of course exception).
MerchantEntity IMerchantRepository.GetMerchantByRegistrationNumber(string companyRegistrationNumber)
{
var db = merchantDataContextProvider.GetMerchantContext();
var merchant = db.Merchants.Include(x => x.MerchantProperty).
SingleOrDefault(x => x.MerchantProperty.CompanyRegistrationNumber == companyRegistrationNumber);
return merchant;
}
I have tried to use DateTime type for Id, the only difference was that it was cutting last 3 numbers, instead whole time part.
Did anyone had same or similar problem? Who to get accurate data when using DB2?
Timestamps as primary key.. not a great idea. If you do however want to use time as your basis for creating an ID of the merchant, you could do this:
var newId = string.format("{0:D19}", DateTime.Now.Ticks)
which will give you a 19-digit long number based on the current time. The problem of course is that if the clock on the PC resets, or you run the program on a different computer, different timezones etc, this strategy will fail.
If you need something that uniquely identifies a row in a table, use GUID's. They're very unique, and the chance of two different processes making the same one is very close to zero
I'm trying to retrieve user selected data from a database. The user can select up to five fields to show in a report and the fields are a mixture of strings, dates and numbers. I cannot convert the data to strings in the SQL code due to other reports being run. Since I don't know the datatype, I can't do datareader.GetSqlString(column), and since I don't know the name of the column the user may have selected, I can't do datareader.GetString(datareader.GetOrdinal(columnName)). Any ideas on how to retrieve the values from the database without knowing either the datatype or the column name?
Thanks in advance.
You can use reader.GetSchemaTable() to get a table of the schema of the data reader or reader.GetType(n) or reader.GetProviderSpecificType(n) to get the datatype of a particular field.
You can then use that information to decide which method to call:
if (reader.GetType(n) == typeof(string))
{
string value = reader.GetString(n);
}
I have table with versioning field of type Timestmap. Now I'm trying to make a query with search by this field, but when I'm passing parameter in next way:
query.SetParameter("TimeStamp", lastTick, NHibernateUtil.Timestamp);
it pass it as DateTime to the sql query. Also tried NHibernateUtil.Binary, but nhibernate pass it as varbinary.
The NHibernate TimestampType specifies:
This is almost the exact same type as the DateTime except it can be used
in the version column, stores it to the accuracy the database supports,
and will default to the value of DateTime.Now if the value is null.
This type is simply not for use with the MS SQL type TIMESTAMP. In fact, that column type is deprecated:
The timestamp syntax is deprecated. This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work, and plan to modify applications that currently use this feature.
rowversion (Transact-SQL)
You should use NHibernateUtil.Binary or NHibernateUtil.BinaryBlob.
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.