I have a table Assessment
which has (among others) two columns, CurrentGrade
and PreviousGrade
, both of which are defined as char(1)
. A grade is a symbol from A to Z.
Now I want to write a query to get the difference between the current grade and the previous grade of all records in Assessment
, to be expressed as a number, eg if previous is A and current is D, then the difference is 3.
I would have done something like this:
var q = db.Assessments.Select(a => new { a.ID, Diff = a.CurrentGrade[0] - a.PreviousGrade[0] });
... except that this doesn't work, because there's no SQL translation for String.getChars
.
And I don't want to do this in local memory, because in my real code, this is just part of a big "where" clause that involves other expressions that must be done in Linq to Entities.
Any recommendations how to do this?
In Linq-To-Entities , you can use SqlFunctions.Ascii
:
using System.Data.Objects.SqlClient;
var result = db.Assessments.Select(a => new { a.id,
Diff = SqlFunctions.Ascii(a.CurrentGrade).Value - SqlFunctions.Ascii(a.PreviousGrade).Value });
Note that if CurrentGrade
is higher (A) than PreviousGrade
(D), you'll get an answer of -3
which is reverse of what you may want... So you may want to multiply by -1
to get the true direction of the grade difference.
var result = db.Assessments.Select(a => new { a.id,
Diff = (SqlFunctions.Ascii(a.CurrentGrade).Value - SqlFunctions.Ascii(a.PreviousGrade).Value) * -1 });
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.