Entity 4.0 Casting Value As DateTime - casting

LINQ to Entity Framework 4.0. SQL Server.
I'm trying to return a list of objects and one of the columns in the database is varchar(255) and contains dates. I'm trying to cast the value to datetime, but I haven't found the solution to that yet.
Example:
List<MyObject> objects = (from c in context.my_table
where c.field_id == 10
select new MyObject()
{
MyDate = c.value // This is varchar, want it to be datetime
}).ToList();
Is this not possible?
Update. This is LINQ to Entity. When trying to convert to DateTime I get:
LINQ to Entities does not recognize the method 'System.DateTime ToDateTime(System.String)' method, and this method cannot be translated into a store expression.

The answer is it's not currently possible with Entity Framework. With LINQ itself it is, just not supported with Entity Framework.

You want DateTime.Parse(c.value) which will take a string containing a date and create a DateTime object out of it.

you can do like this
Date=DateTime.Parse(text)

read, And the best bet would be using your result and then Converting to date time. Like below,
static void Main(string[] args)
{
Console.WriteLine(getme());
Console.ReadLine();
}
private static DateTime getme()
{
List<string> ss = new List<string>();
ss.Add("11/11/2010");
var r = from l in ss
select new { date = Convert.ToDateTime(l) };
return r.FirstOrDefault().date;
}

Related

How to check the date part in a Java collection Arraylist?

I have one ArrayList:
List<Date> date= ArrayList<Date>();
date.add(2017-07-26 09:27:33);
date.add(2017-07-28 10:11:33);
date.add(2017-07-25 08:27:33);
date.add(2017-07-25 07:27:33);
Now I am testing
date.contains(2017-07-25 11:27:33); //should come true
I want to check on the basis only the only date not time. How can I check only base of date not time?
First of all your code can not compile.
Lets change it to valid java code and compare two date only without time portion:
List<Date> date = new ArrayList();
DateFormat format = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss", Locale.ENGLISH);
DateFormat compareFormat = new SimpleDateFormat("yyyy-mm-dd", Locale.ENGLISH);
try {
date.add(format.parse("2017-07-26 09:27:33"));
date.add(format.parse("2017-07-28 10:11:33"));
date.add(format.parse("2017-07-25 08:27:33"));
date.add(format.parse("2017-07-25 07:27:33"));
Date searchedDate = format.parse("2017-07-26 16:27:33");
boolean isExist = date.stream().anyMatch(d -> compareFormat.format(d).equals(compareFormat.format(searchedDate)));
System.out.println(isExist);
} catch (ParseException e) {
e.printStackTrace();
}
Also there are another solutions to compare date without time part, take a look another solutions : How to compare two Dates without the time portion?

Using Univocity, how can I convert a date string value to a Date type in Java

I'll like to parse column zero in a csv file to a particular datatype, in this example a Date Object.
The method below is what I use currently to parse a csv file but I don't know how to incorporate this requirement.
import java.sql.Date;
public class Data {
#Parsed(index = 0)
private Date date;
}
}
public <T> List<T> convertFileToData(File file, Class<T> clazz) {
BeanListProcessor<T> rowProcessor = new BeanListProcessor<>(clazz);
CsvParserSettings settings = new CsvParserSettings();
settings.setProcessor(rowProcessor);
settings.setHeaderExtractionEnabled(true);
CsvParser parser = new CsvParser(settings);
parser.parseAll(file);
return rowProcessor.getBeans();
}
All you need is to define the format(s) of your date and you are set:
#Format(formats = {"dd-MMM-yyyy", "yyyy-MM-dd"})
#Parsed(index = 0)
private Date date;
}
As an extra suggestion, you can also replace a lot of your code by using the CsvRoutines class. Try this:
List<T> beanList = new CsvRoutines(settings).parseAll(clazz, file);
Hope it helps.

How to efficiently convert DataSet.Tables to List<DataTable>?

I see many posts about converting the table(s) in a DataSet to a list of DataRows or other row data but I was unable to find anything about this question. This is what I came up with using .Net 3.0:
public static List<DataTable> DataSetToList(DataSet ds)
{
List<DataTable> result = new List<DataTable>();
foreach (DataTable dtbl in ds.Tables)
{
result.Add(dtbl);
}
return result;
}
Is there a better way, excluding an extension method?
Thanks
Based on Why LINQ casting with a Data.DataTableCollection this will work;
List<DataTable> result = new List<DataTable>(ds.Tables.Cast<DataTable>())
IEnumerable<DataTable> sequence = dt.AsEnumerable();
or
List<DataTable> list = dt.AsEnumerable().ToList();

T4 Templates : Reading resulting columns of a stored procedure table

I am learning T4 templates right now, and all examples I got on internet is about using the tables for code generation. I want to use stored procedure result columns to generate automated UI, is it possible? OR I have to create view for same query? in that case, how to read from view?
Thanks in advance.
I got the solution and here is how you can generate a rad grid directly from the sp name
<#
'requires: <## assembly name="System.Data" #>
dim Server as new Server(".\sqlexpress")
dim database as new Database(server, "xxxx")
dim strSpName as String= "sp_xxxx"
Dim dt as System.Data.DataTable= database.ExecuteWithResults("exec sp_GetEquipment").Tables(0)
dim ctlName as String = "grdEqp"
#>
<telerik:RadGrid ID="grd" runat="server" Skin="Web20" AutoGenerateColumns="false">
<MasterTableView>
<Columns>
<#
For Each column As System.Data.DataColumn In dt.Columns
#><telerik:GridBoundColumn DataField="<#=column.ColumnName #>" HeaderText="<#=column.ColumnName #>"/>
<#Next#>
</Columns>
</MasterTableView>
</telerik:RadGrid>
If you don't actually want to execute the stored procedure as various stored procedures have a number of different parameters passed then you could use the sp_describe_first_result_set system stored procedure to return the columns of the result set assuming there is just one.
/// <summary>
/// Returns table for which stored procedures need to be generated.
/// </summary>
string TableName = "usp_getNominalCode";
string SchemaName = "Financial";
DataTable DataTable
{
get
{
if (_table == null)
{
Server server = new Server(new ServerConnection(new SqlConnection(this.ConnectionString)));
SqlConnectionStringBuilder connectionStringBuilder = new SqlConnectionStringBuilder(this.ConnectionString);
Database database = new Database(server, connectionStringBuilder.InitialCatalog);
DataSet storedProcedureColumns = database.ExecuteWithResults("sp_describe_first_result_set #tsql= " + "'[" + SchemaName + "]" + ".[" + TableName + "]'");
_table = storedProcedureColumns.Tables[0];
}
return _table;
}
}
DataTable _table;
You can then query this table for it's structure like the other answer but it'll be a little more generic

Why does this unit test fail when testing DateTime equality?

Using NUnit 2.2 on .NET 3.5, the following test fails when using DateTime.Equals. Why?
[TestFixture]
public class AttributeValueModelTest
{
public class HasDate
{
public DateTime? DateValue
{
get
{
DateTime value;
return DateTime.TryParse(ObjectValue.ToString(), out value) ? value : new DateTime?();
}
}
public object ObjectValue { get; set; }
}
[Test]
public void TwoDates()
{
DateTime actual = DateTime.Now;
var date = new HasDate {ObjectValue = actual};
Assert.IsTrue(date.DateValue.Value.Equals(actual));
}
}
The dates aren't equal. TryParse drops some ticks. Compare the Tick values.
For one test run:
Console.WriteLine(date.DateValue.Value.Ticks);
Console.WriteLine(actual.Ticks);
Yields:
633646934930000000
633646934936763185
The problem isn't really TryParse, but actually ToString().
A DateTime object starts with precision (if not accuracy) down to millionth of seconds. ToString() convertsit into a string, with precision only to a second.
TryParse is doing the best it can with what it is given.
If you add a format specifier (along the lines of "yyyy-MM-dd HH:mm:ss.ffffff"), it should work.
To specify a format that includes all the precision, you can use the String.Format() method. The example that James gives would look like this:
String.Format("{0:yyyy-MM-dd HH:mm:ss.ffffff}", ObjectValue);
I don't know what that will do when you pass it something that's not a date.
Perhaps a simpler approach is to add a special case when you've already got a date object:
public DateTime? DateValue
{
get
{
DateTime value = ObjectValue as DateTime;
if (value != null) return value;
return DateTime.TryParse(ObjectValue.ToString(), out value) ? value : new DateTime?();
}
}
public DateTime? DateValue
{
get
{
DateTime value;
bool isDate = DateTime.TryParse(ObjectValue.ToString(), out value);
return isDate ? new DateTime?(value) : new DateTime?();
}
}
I don't know if this is the same in .NET, but in Java the equals often will only compare if the instances are the same, not if the values are the same. You'd instead want to use compareTo.