How to return DateTimeOffset type with Linq - linq

how to return DateTimeOffset with a Linq query.
I need to get a due date from a table of type DateTimeOffset
public DateTimeOffset GetLastDate(Guid Id, Guid AppId)
{
var q = from k in context.Inspections
where k.Id == Id || k.AppId == AppId
select k.Duedate;
return q;
}
cannot implicitly convert system.Linq.IQueryable to System.DateTimeOffset

The problem is that your query will return an IQueryable<T>, with the type being the type of Duedate.
If Duedate is a DateTimeOffset, you could return the first result (Where can return multiple matches) via:
var q = from k in context.Inspections
where k.Id== Id||k.AppId== AppId
select k.Duedate;
DateTimeOffset? value = q.First();
if (value.HasValue)
return value.Value;
else // found NULL in DB! Do something in this case...
throw new ApplicationException("Null offset found");
// Alternatively, you could use some default value (this uses "Now"):
// return value ?? DateTimeOffset.Now;

Related

Return a column value with the input ID

I was trying to return a column value in a table called with its ID .
public String PenTypes(int?id, Pen pen)
{
int num;
var query = from d in db.Pens
where d.ID == 1
select d.Type;
num=Convert.ToInt(query);
return num;
I have no clue as to where i'm going wrong. I do know its simple, but I'm really new to using Entity Framework. Any Help would be appreciated.
I suggest you to use DbSet<TEntity>.Find method if you want to get entity by id:
var pen = db.Pens.Find(id);
if (pen == null)
// handle case when pen is not found
return pen.Type; // if type is string, then you possibly need to parse it
Or you can use FirstOrDefault/SingleOrDefault:
var pen = db.Pens.FirstOrDefault(p => p.ID == id);
Your current code has several problems:
query will have type of IQueryable<T> (where T is type of pen.Type property). This value cannot be converted to integer
id should not be nullable if you are searching by primary key
if num is integer, then return type of method should be int instead of string

Compare a linq value (int) to an int List using where clause

I have a linq query which joins a couple of tables and returns the value into an object. The query was working fine, till i added a where clause to in. Aftre the where clause, my query returns null.
Here's the code:
List<Int32> resourceSupervisorIdList = new List<Int32>();
resourceSupervisorIdList.Add(searchCriteriaTimesheet.ResourceId);
foreach (resource res in allSubordinateResources)
{
if (!resourceSupervisorIdList.Contains(res.id_resource))
resourceSupervisorIdList.Add(res.id_resource);
}
using (tapEntities te = new tapEntities())
{
var timesheetAll = (from tsh in te.timesheet_header
join rs in te.resources on tsh.id_resource equals rs.id_resource
join tsd in te.timesheet_detail on tsh.id_timesheet equals tsd.id_timesheet
where (resourceSupervisorIdList.Contains(rs.id_resource_supervisor))
select new TimesheetHeaderDetailsItem()
{
OrganizationId = rs.id_organization,
ProjectId = tsd.id_project,
StartDate = tsh.dte_period_start,
EndDate = tsh.dte_period_end,
ApprovedDate = tsh.dte_approved,
RejectedDate = tsh.dte_rejected,
SubmittedDate = tsh.dte_submitted,
});
if (timesheetAll == null || timesheetAll.Count() == 0)
{
return result;
}
}
Now, after adding the where clause, the code runs into the if condition. There are matching records in the table, but still i'm not able to get any records.
rs.id_resource_supervisor
is of type int in the mysql db.

convert Enumerable row collection <short> to short

I have this error can't implicitly convert Enumerable row collection <short> to short in this line of code:
Month = (from item in query select (short)item.Month);
I want to know why and why I can't find distinct() or count method in query variable.
here is my method:
public bool IsEnableAccPosting(
string CompanyCode, DateTime FromDate, DateTime ToDate, out short Month)
{
try
{
o_dmDebitAccounts = new dmDebitAccounts(sysInfo);
bool IsEnable = false;
DataTable dt = o_dmDebitAccounts.GetDebitInterestAccPeriods(CompanyCode);
var query = from data in dt.AsEnumerable()
where data.Field<DateTime>("StartDate") == FromDate &&
data.Field<DateTime>("EndDate") == ToDate
select new
{
Month = Convert.ToInt16(data.Field<short>("Month")),
Year = Convert.ToInt16(data.Field<short>("Year"))
};
Month = (from item in query select (short)item.Month); //heres the error
The field is already typed as an Int16 in the linq query that is performing the operation. You dont need to cast it.
try the following code taken from here
if (query.Any())
{
var result = query.First();
// Console.WriteLine("Results: {0}", result.Month);
Month = result.Month;
}

H2 Oracle decode function

In H2, I have written a Java decode function. It works with the code:
String sql = "select decode(1.0,2.0,3.0,4.0) from dual ;";
PreparedStatement stmt = connection.prepareStatement(sql);
ResultSet resultSet = (ResultSet) stmt.executeQuery();
But the code
String sql = "select 6.0 - decode(1.0,2.0,3.0,4.0) from dual ;";
gives the error:
org.h2.jdbc.JdbcSQLException: Hexadecimal string with odd number of characters: "6.0"; SQL statement:
select 6.0 - decode(1.0,2.0,3.0,4.0) from dual ; [90003-157]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:327)
at org.h2.message.DbException.get(DbException.java:167)
at org.h2.message.DbException.get(DbException.java:144)
at org.h2.util.StringUtils.convertHexToBytes(StringUtils.java:943)
at org.h2.value.Value.convertTo(Value.java:826)
at org.h2.expression.Operation.getValue(Operation.java:108)
at org.h2.command.dml.Select.queryFlat(Select.java:518)
at org.h2.command.dml.Select.queryWithoutCache(Select.java:617)
at org.h2.command.dml.Query.query(Query.java:298)
at org.h2.command.dml.Query.query(Query.java:268)
at org.h2.command.dml.Query.query(Query.java:37)
at org.h2.command.CommandContainer.query(CommandContainer.java:80)
at org.h2.command.Command.executeQuery(Command.java:181)
at org.h2.jdbc.JdbcPreparedStatement.executeQuery(JdbcPreparedStatement.java:96)
My decode function is as:
public final static Value decode(Value expression, Value ... paramValues) {
boolean param = true;
boolean hit = false;
Value returnValue = null;
Value defaultValue = null;
// Walk through all parameters, alternately the 'param' and corresponding 'value'.
// If 'param' is equal the expression, then return the next 'value'.
// If no hit, the return the last 'param' value as default value.
for (Value str : paramValues) {
if (param) {
defaultValue = str; // In case this is the last parameter.
// Remember the hit. The next value will be returned.
hit = (MiscUtil.equals(expression, str));
} else {
if (hit) {
returnValue = str;
break; // return str;
}
defaultValue = null;
}
param = ! param;
}
return (returnValue==null) ? defaultValue : returnValue;
}
Is there anything wrong with my decode function?
I have tried to return Object instead of Value in the decode function, and added this code at the end:
Object returnObject=null;
if (returnValue instanceof ValueDecimal) {
returnObject = ((ValueDecimal)returnValue).getBigDecimal();
} else if (returnValue instanceof ValueString) {
returnObject = ((ValueString)returnValue).getString();
} else if (returnValue instanceof ValueDate) {
returnObject = ((ValueDate)returnValue).getDate();
}
return returnValue;
But the I got:
org.h2.jdbc.JdbcSQLException: Data conversion error converting "aced0005737200146a6176612e6d6174682e426967446563696d616c54c71557f981284f0300024900057363616c654c0006696e7456616c7400164c6a6176612f6d6174682f426967496e74656765723b787200106a6176612e6c616e672e4e756d62657286ac951d0b94e08b020000787000000001737200146a6176612e6d6174682e426967496e74656765728cfc9f1fa93bfb1d030006490008626974436f756e744900096269744c656e67746849001366697273744e6f6e7a65726f427974654e756d49000c6c6f776573745365744269744900067369676e756d5b00096d61676e69747564657400025b427871007e0002fffffffffffffffffffffffefffffffe00000001757200025b42acf317f8060854e0020000787000000001287878"; SQL statement:
select 6.0 - cast(decode(1.0,2.0,3.0,4.0) as double) xxx from dual ; [22018-157]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:327)
at org.h2.message.DbException.get(DbException.java:156)
at org.h2.value.Value.convertTo(Value.java:855)
at org.h2.expression.Function.getSimpleValue(Function.java:733)
at org.h2.expression.Function.getValueWithArgs(Function.java:893)
at org.h2.expression.Function.getValue(Function.java:432)
at org.h2.expression.Operation.getValue(Operation.java:113)
at org.h2.expression.Alias.getValue(Alias.java:35)
...
I also did some try with ValueExpression without luck.
Full support for decode in H2 would be the best solution. Is that something you can provide Thomas?
H2 thinks the data type is JAVA_OBJECT, and therefore wants to convert the parameters (6.0 and the result of the decode) to JAVA_OBJECT, which means first convert to a byte array. This fails.
I didn't test it myself, but explicit CAST should work:
select 6.0 - cast(decode(1.0,2.0,3.0,4.0) as double) from dual
It's a bit ugly I know.

linq combined column search

I want to search records which two column combination equals to the parameter, why it does not work?
public RDCheck SearchByUserPlusId(string uid)
{
RDCheckDataContext dc = new RDCheckDataContext(_connString);
var query = (from r in dc.RDChecks
where (r.login + r.id).Equals(uid)
select r).FirstOrDefault();
return query;
}
for example, one record in table is
id:4/login:test
So I pass parameter uid=test4 but it returns null, why?
Use ToString() before the concatenation
public RDCheck SearchByUserPlusId(string uid)
{
RDCheckDataContext dc = new RDCheckDataContext(_connString);
var query = (from r in dc.RDChecks
where (r.login.ToString() + r.id.ToString()).Equals(uid)
select r).FirstOrDefault();
return query;
}

Resources