How to catch null while summarizing records in EF6 - entity-framework

next problem with Linq/EF6 queries.
I simply like to build a sum of some decimal fields:
var offsetHours1 = (from os in db.TimesheetOffsets
where (os.EmployeeId == employeeId && os.OffsetDate <= DateTime.Today)
select new
{
offset = os.OffsetHours
}).Sum(h=>h.offset);
So far it works, if I have records to sum but if the query returns null or no records, I get a System.InvalidOperationException
Is there an elegant way to summarize records in one step, so if there are no records, 0 is returned?
Thanks, Carsten

There's a quirk with the Sum extension method. As OffsetHours is a decimal, the overload of Sum you'll be using is Sum(..., decimal) which has this behaviour. To avoid it you can cast the value to a decimal? (nullable). With this you'll be using a different Sum that returns a nullable decimal and is OK with empty lists;
You can for example do this;
var offsetHours1 = (from os in db.TimesheetOffsets
where (os.EmployeeId == employeeId && os.OffsetDate <= DateTime.Today)
select os.OffsetHours)
.Sum(h => (decimal?)h);
Edit:
Removed unnecessary creation of anonymous type.

Related

How to format a number in Entity Framework LINQ (without trailing zeroes)?

In a SQL Server database I have a column of decimal datatype defined something like this:
CREATE TABLE MyTable
(
Id INT,
Number DECIMAL(9, 4)
)
I use Entity Framework and I would like to return column Number converted to a string with only the digits right of the decimal separator that are actually needed. A strict constraint is that a result must be an IQueryable.
So my query is:
IQueryable queryable = (
from myTable in MyDatabase.NyTable
select new
{
Id = myTable.Id,
Number = SqlFunctions.StringConvert(myTable.Number,9,4)
}
);
The problem with is that it always convert number to string with 4 decimals, even if they are 0.
Examples:
3 is converted to "3.0000"
1.2 is converted to "1.2000"
If I use other parameters for StringConvert i.e.
SqlFunctions.StringConvert(myTable.Number, 9, 2)
the results are also not OK:
0.375 gets rounded to 0.38.
StringConvert() function is translated into SQL Server function STR.
https://learn.microsoft.com/en-us/sql/t-sql/functions/str-transact-sql?view=sql-server-2017
This explains the weird results.
In the realm of Entity Framework and LINQ I was not able to find a working solution.
What I look for is something like C# function
String.Format("0.####", number)
but this cannot be used in a LINQ query.
In plain simple SQL I could write my query like this
SELECT
Id,
Number = CAST(CAST(Number AS REAL) AS VARCHAR(15))
FROM
MyTable
I have not managed to massage LINQ to produce query like that.
A workaround would be to forget doing this in LINQ, which is quite inflexible and messy thing, borderline on useless and just return type DECIMAL from database and do my formatting on a client side before displaying. But this is additional, unnecessary code and I would hate to di it that way if there perhaps is a simpler way via LINQ.
Is it possible to format numbers in LINQ queries?
I would absolutely return a decimal from he database and format it when needed. Possible directly after the query. But usually this is done at display time to take into account culture specific formatting from the the client.
var q =
(from myTable in MyDatabase.NyTable
select new
{
Id = myTable.Id,
Number = myTable.Number
})
.AsEnumerable()
.Select(x => new { Id = x.Id, Number = x.Number.ToString("G29") });

Update with ISNULL and operation

original query looks like this :
UPDATE reponse_question_finale t1, reponse_question_finale t2 SET
t1.nb_question_repondu = (9-(ISNULL(t1.valeur_question_4)+ISNULL(t1.valeur_question_6)+ISNULL(t1.valeur_question_7)+ISNULL(t1.valeur_question_9))) WHERE t1.APPLICATION = t2.APPLICATION;
I know you cannot update 2 tables in a single query so i tried this :
UPDATE reponse_question_finale t1
SET nb_question_repondu = (9-(COALESCE(t1.valeur_question_4,'')::int+COALESCE(t1.valeur_question_6,'')::int+COALESCE(t1.valeur_question_7)::int+COALESCE(t1.valeur_question_9,'')::int))
WHERE t1.APPLICATION = t1.APPLICATION;
But this query gaves me an error : invalid input syntax for integer: ""
I saw that the Postgres equivalent to MySQL is COALESCE() so i think i'm on the good way here.
I also know you cannot add varchar to varchar so i tried to cast it to integer to do that. I'm not sure if i casted it correctly with parenthesis at the good place and regarding to error maybe i cannot cast to int with coalesce.
Last thing, i can certainly do a co-related sub-select to update my two tables but i'm a little lost at this point.
The output must be an integer matching the number of questions answered to a backup survey.
Any thoughts?
Thanks.
coalesce() returns the first non-null value from the list supplied. So, if the column value is null the expression COALESCE(t1.valeur_question_4,'') returns an empty string and that's why you get the error.
But it seems you want something completely different: you want check if the column is null (or empty) and then subtract a value if it is to count the number of non-null columns.
To return 1 if a value is not null or 0 if it isn't you can use:
(nullif(valeur_question_4, '') is null)::int
nullif returns null if the first value equals the second. The IS NULL condition returns a boolean (something that MySQL doesn't have) and that can be cast to an integer (where false will be cast to 0 and true to 1)
So the whole expression should be:
nb_question_repondu = 9 - (
(nullif(t1.valeur_question_4,'') is null)::int
+ (nullif(t1.valeur_question_6,'') is null)::int
+ (nullif(t1.valeur_question_7,'') is null)::int
+ (nullif(t1.valeur_question_9,'') is null)::int
)
Another option is to unpivot the columns and do a select on them in a sub-select:
update reponse_question_finale
set nb_question_repondu = (select count(*)
from (
values
(valeur_question_4),
(valeur_question_6),
(valeur_question_7),
(valeur_question_9)
) as t(q)
where nullif(trim(q),'') is not null);
Adding more columns to be considered is quite easy then, as you just need to add a single line to the values() clause

Add value of subquery in Entity Framework

I have a really strange situation with the subquery.
Value of subquery is calculated but assigned value to property is different
var ozForAllViews = from oz in dbContext.oz
where
oz.TId == 6050
select
new ozForAllView
{
ozId = oz.ozId,
Ilosc = oz.Ilosc - (from pz in dbContext.pz
where
pz.Aktywny &&
pz.ozId == oz.ozId
select pz).Sum(z=> (decimal?) z.Ilosc) ?? 0
};
My property Ilosc is not calculated properly, value in DB equals 5.
But returned value is always 0.
Why is that oz.Ilosc is not subtracted from subquery?
I mean that 5 - 0 should equals 5.
You should surround the expression that calculates the subtracted amount by parentheses:
from oz in dbContext.oz
where oz.TId == 6050
select
new ozForAllView
{
ozId = oz.ozId,
Ilosc = oz.Ilosc - ((from pz in dbContext.pz
where
pz.Aktywny &&
pz.ozId == oz.ozId
select pz).Sum(z=> (decimal?) z.Ilosc) ?? 0)
};
This is because the query is translated into SQL. In SQL, if one part of an expression is null, the whole expression is null. Your query is translated such that oz.Ilosc - (from ... (decimal?) z.Ilosc) is evaluated as one expression. That part becomes null when the subtracted amount is null and hence it will be returned as 0.
It's confusing because in plain C# code, the behavior would be different. There the ?? 0 part would be applied to the subtracted amount only.

Count Group Ordinal in LINQ to Dataset

I have an old FoxPro program that does a SQL query which includes the following:
SELECT Region,
Year AS yr_qtr,
SUM(Stock) AS inventory
**...
COUNT(Rent) AS rent_ct
FROM
**...
GROUP BY Region, Year
ORDER BY Region, Year
INTO CURSOR tmpCrsr
The query is against a .DBF table file, and includes data from an Excel file. I've used both to populate an enumeration of user-defined objects in my C# program. (Not sure .AsEnumerable is needed or not.) I then attempt to use LINQ to Dataset to query the list of user objects and create the same result set:
var rslt1 = from rec in recs_list //.AsEnumerable()
group rec by new {rec.Region, rec.Year} into grp
select new
{
RegName = grp.Key.Region,
yr_qtr = grp.Key.Year,
inventory = grp.Sum(s => s.Stock),
// ...
rent_count = grp.Count(r => r.Rent != null)
};
This gives me the warning that "The result of the expression is always 'true' since a value of type 'decimal' is never equal to 'null' of type 'decimal'" for the Count() of the Rent column.
This makes sense, but then how do I do a count exclusive of the rows that have a value of .NULL. for that column in the FoxPro table (or NULL in any SQL database table, for that matter)? I can't do a null test of a decimal value.
If rent is based off of a column which is not a nullable value, then checking for null makes no sense which I believe the compiler accurately shows. Change the line to
rent_count = grp.Count(r => r.Rent != 0)
instead.
For if the code is actuall nullable such as:
Decimal? rent;
That would make checking rent against null valid. If that is the case then the line would be:
rent_count = grp.Count(r => (r.Rent ?? 0) != 0)
where null coalesding operator ?? can be used. Which states if r.rent is null, use the value 0 (or any value you want technically) for r.Rent. in the next process.

LINQ Query and DateTimes

I'm trying to get the Sum() from an Entityset<MyObject> with the next query.
(from MyObject p in SelectedObject.MyObjectEntitySet
where p.AColumn.HasValue &&
p.ADate >= dateTimeValue &&
p.ADate <= dateTimeValue2
select p.AColumn.Value).Sum();
with no luck retrieving correct sum.
Any Ideas?
[EDIT] OK WORKED!
You can troubleshoot the query by breaking it up into its constituent parts, and examining the output of each part:
var entitySet = SelectedObject.MyObjectEntitySet;
var entitySetWithValues = entitySet.Where(p => p.AColumn.HasValue);
var entitySetGreater = entitySetWithValues.Where(p => p.ADate >= DateTimeValue);
...and so forth.
If you see the list of overloads, the Sum method is over numeric values (decimal, float, int, double, long, etc). The selector has to be a function that takes a DateTime and returns a numeric value.
[edit]
Sorry, I didn't realize that AColumn was numeric.