sql to linq query convert - c#

I try to convert SQL to LINK query
I try this
SQL query
Select name, count(*) from tblVehicles
WHERE MID = 23065 and name<> '' Group By name
LINQ query
var re = (from vehvoila in DB.tblVehicles
where vehvoila.MID='23065' && vehvoila.name
group vehvoila by new{vehvoila.name} into g
select new
{
g.Key.name,
cnt=g.Select(t=>t.name).Count()
});
How I use <> in LINQ ?

What could work for you is
where vehvoila.MID == "23065" && !(vehvoila.name == null || vehvoila.name == "")
or just
where vehvoila.MID == "23065" && vehvoila.name != ""
String.IsNullOrEmpty in not supported in Linq-SQL:
Method 'Boolean IsNullOrEmpty(System.String)' has no supported translation to SQL.

Related

Entity Framework - Oracle - Compare nullable DateTime using linq is not working

I'm using Entity Framework with Oracle and I'm trying to do a query using linq comparing a nullable DateTime, but when I do this comparation, the query gives me wrong result.
I execute the equivalent query in PL/SQL Developer and I have the correct result.
Here is my code
using (var context = new CorporativoContext())
{
context.Database.Log = Console.Write;
var parametro = (from p in context.PARAMETRO
join pv in context.PARAMETRO_VALOR on p.Id equals pv.Id
where p.Descricao == descricaoParametro && pv.InicioVigencia <= DateTime.Now && pv.FimVigencia == null
select pv).FirstOrDefault();
return parametro;
}
the property"FimVigencia" is nullable DateTime (DateTime? FimVigencia) and when I compare it to null, the query result returns nothing, but if I remove this comparation, the query gives me an object with null value for property "FimVigencia".
Can anyone help me?
Found the solution. I will post here for anyone who have same problem
I need to use DbFunctions.TruncateTime to compare to null
here is my code:
(from p in _context.PARAMETRO
join pv in _context.PARAMETRO_VALOR on p.Id equals pv.Id
where p.Descricao == descricaoParametro && pv.InicioVigencia <= DateTime.Now &&
(DbFunctions.TruncateTime(pv.FimVigencia) == null || pv.FimVigencia >= DateTime.Now)
select pv).FirstOrDefault();

Linq to SQL issue with where clause

I am trying to create a where clause in Linq to SQL using the following logic
if #supplierid is null return all records.
if #supplierid is not null return where supplierid is equals to #supplierid.
and the one that is creating an issue:
if #supplierid ==0 return all records where supplierid is null
I tried writing this like
var answers =
from thisChargeableService in this.GetAll()
where
(
(
(supplierId == null) ||
(
((supplierId < 1) && (thisChargeableService.SupplierId == null)) ||
((supplierId != null) && (thisChargeableService.SupplierId == supplierId.Value))
)
));
This works with the first two conditions but when #supplierid = 0, nothing is returned.
Any help with this would be much appreciated
edit
Basically I have a dropdown of N/A with an id of 0. I have used this to identify that an option has been selected from dropdown and the user is targeting all rows where the supplier id is N/A.
The database contains no entries with 0 as the supplierid, so instead I am trying to target this with where the supplierid is null or the below in SQL
SELECT * FROM ChargeableService
WHERE
(#supplierid is null)
OR
(
(#supplierid is not null and supplierid = #supplierid) or
(#supplierid = 0 AND supplierid is null)
)
With Linq, there is no need to try to build one query to do all. Instead you can build your expression in buts and let deferred execution build and execute the correct sql.
So, this is the way I would do it.
var answers = this.GetAll().AsQueryable();
if (supplierId.HasValue && (supplierId.Value != 0))
answers = answers.Where(a=>a.SupplierId == supplierId.Value);
if (supplierId.HasValue && (supplierId.Value == 0))
answers = answers.Where(a=>!a.SupplierId.HasValue);
I've taken your query and run it against some similar data and the following works:
var answers =
from thisChargeableService in this.GetAll()
where
(
supplierId == null ||
(supplierId == 0 && thisChargeableService.SupplierId == null) ||
(supplierId > 0 && thisChargeableService.SupplierId == supplierId)
)
select thisChargeableService;

How can i calculate sum of this linq to sql query?

I'm beginner in linq to sql, I using the c# linq to sql and wrote this query:
var query_find = (from t in behzad.Interconnect_Traffic_Analysis_Details
where t.FILEID == FILE_ID && t.code_operator.Trim() == item.code_operator.Trim()
select new { t.moddat }).ToList();
I want to calculate sum of the t.moddat column, how can I convert this query to sum the values? Thanks.
t.moddat is a nvarchar(max) datatype and save into that double datatype value.
Try this
var query_find = (from t in behzad.Interconnect_Traffic_Analysis_Details
where t.FILEID == FILE_ID && t.code_operator.Trim() == item.code_operator.Trim()
select new
{
sum= t.moddat
}).ToList();
var sum= query_find.Sum(x => Convert.ToDouble(x.sum));

How do I translate this SQL query to Lambda or LINQ that uses (where is null)

I've been trying to modify some rows of data in SQL to test in my application and I've noticed my query in Lambda brings back 0 rows when I am expecting 2387 row. The source of the problem is I am using parenthesis in a WHERE clause in SQL to look at some null values. This is the SQL query:
SQL
-- THIS WORKS!
select * from vwAppsWithIssues
where fld1stCheckAllocatedTo = 'nicholasg' and fldStage = 1
and (fldStopStartDate is null or fldStopEndDate is not null)
-- The query was originally this (doesn't return rows)
select * from vwAppsWithIssues
where fld1stCheckAllocatedTo = 'nicholasg' and fldStage = 1
and (fldStopStartDate = null or fldStopEndDate <> null)
LAMBDA query that returns 0 rows
public static int GetApplicationsFirstCount(string UserId)
{
try
{
using (IME_CheckOffEntities IME_CheckOffEntities = new IME_CheckOffEntities())
{
return IME_CheckOffEntities.vwAppsWithIssues
.Where(a => a.fld1stCheckAllocatedTo == UserId && a.fldStage == 1 && (a.fldStopStartDate == null || a.fldStopEndDate != null))
.ToList().Count;
}
}
catch (Exception ex)
{
throw;
}
}
Update
Using LINQPad I have written this expression:
VwAppsWithIssues
.Where (v => v.Fld1stCheckAllocatedTo == "nicholasg"
&& v.FldStage == 1
&& (v.FldStopStartDate == null || v.FldStopEndDate != null)).Count()
that generates this sql
SELECT COUNT(*) AS [value]
FROM [vwAppsWithIssues] AS [t0]
WHERE ([t0].[fld1stCheckAllocatedTo] = #p0) AND ([t0].[fldStage] = #p1) AND (([t0].[fldStopStartDate] IS NULL) OR ([t0].[fldStopEndDate] IS NOT NULL))
So now that I have some lambda that I think will work, I simply copy it to visual studio.
var count = IME_CheckOffEntities.vwAppsWithIssues
.Where(v => v.fld1stCheckAllocatedTo == "nicholasg" && v.fldStage == 1 && (v.fldStopStartDate == null || v.fldStopEndDate != null)).Count();
It still returns only 0 rows?! I am passing in the right userId in C# as well.
My count in c# also returns 0 rows. Any idea how I can rewrite this C# query?
from linqpad, on one of my schema
from
f in Files
where
f.PubDate == null || f.FilingDate != null
select
f.IdFile
is translated as follow
SELECT
[Extent1].[idFichier] AS [idFichier]
FROM [dbo].[tableF] AS [Extent1]
WHERE ([Extent1].[datePubliF] IS NULL) OR ([Extent1].[dateDepotF] IS NOT NULL)
so, in your case, are you, for example, sure of the UserId value ?

linq version of sql with CAST to smallmoney

I am trying to make a linq query to execute this query. The column Additional Data is nvarchar(20) - so linq is reading it as a string
this works fine in SSMS
select SUM(CAST(AdditionalData as smallmoney)) from TransTable
where ActionID = #actID and UserID = uID;
this is my failed attempt at a linq version ( Decimal.Parse() can not be converted to sql from linq i guess)
(from a in Context.TransTable
where a.ActionID == action.ActionID && a.UserID == (long)userId
select decimal.Parse(a.AdditionalData)).Sum();
If the result set isn't too large you could parse the value on the client.
decimal value;
var sum = (from a in Context.TransTable
where a.ActionID == action.ActionID && a.UserID == (long)userId
select a.AdditionalValue).ToList().
Select(x => decimal.TryParse(x, out value) ? value : 0).Sum();

Categories