From T-Sql to Linq-to-SQL - sql-server

I need a very simple query in my aplication but I can't figure out how to translate it into Linq-to-SQL because I need it in an asp.net application.
It is neccesery that it is a lambda expression because of internal procedures.
In T-SQL it looks like this:
select top 1 [datum]
from Test
where Datum <> (select max (Datum) from Test)
Sorry for the stupid question in advance.

You can use the Max function inline with the query
var result = Test
.Where(t => t.Datum != Test.Max(t1 => t1.Datum))
.Select(t => t.Datum)
.FirstOrDefault();

To apply such query using lambda expression first you need to fetch all records from table test and the list that you get can be used to get the output you want.
Sample query would be as follows after you fetch the list from the database.
var test= Tests
.OrderByDescending(e => e.datum)
.Skip(1)
.First();

Related

Using SqlKata from an existing Query

I have existing queries used for jobs that run within services to generate reports. Simple things like
"Select * from Transactions"
The jobs will then append parameters to these queries based on preset rules, like Date>Yesterday etc. SqlKata looks like it can do this but I'm not sure how to instantiate the Query object from an existing query. Is something like this possible?
Dim Qry as new Query("Select * from Transactions").OrderByDesc("Date")
Qry.Where("Date", ">", Date.Now().AddDays(-1))
return Qry.Get()
The closest thing that you can do in this case is to wrap the inner query and add conditions on top of it, you can use the SubQuery or CTE approach here.
Something like this, this in C# but the idea is the same.
var existingSql = "select * from transactions";
var query = new Query().FromRaw($"({existingSql}) as inner")
.Where("date", ">=", DateTime.UtcNow.Date);
checkout this example on playground

Dapper, SqlBuilder extension and Order By descending

I am trying to build a simple query that retrieves data in descending order using Dapper. The database is MySql if that's important.
This is the code I used:
var builder = new SqlBuilder();
var sql = #$"SELECT * FROM table t /**orderby**/ LIMIT #paramSkip, #paramTake";
var template = builder.AddTemplate(sql);
builder.OrderBy("#paramOrderBy DESC", parameters: new
{
paramOrderBy = orderBy,
});
// Limit
builder.AddParameters(parameters: new
{
paramSkip = skip,
paramTake = take
});
return Connection.QueryAsync<TableModel>(
template.RawSql, template.Parameters,
transaction: Transaction
);
This always returns data in ascending order. DESC is just ignored. I tried using the DESC keyword in the query or as parameter but the result was the same.
Only thing that worked was putting order parameters and DESC keyword in query itself (by string interpolation)
(Edit: Typos and text simplification)
You need your query to look something like this:
... ORDER BY <Column name> DESC ...
A column name cannot be parameterized, so you need to insert it into the query something like this:
builder.OrderBy($"{orderBy} DESC");
If your orderBy originates from the user in any way, be sure to sanitize it first to prevent SQL injection. You could - for instance - keep a list of valid column names and validate against it.

Need my SQL Query translated to Entity Framework code query

I need to able to translate my sql query to EF code, my sql query is using one where statement of IN operator and not sure how to also do that in EF.
I have tried doing a EF code the follwing code below but is not working.
private ManufacturingDbContext _manufacturingDbContext;
public List<string> GetManufacturerOrders()
{
var context = _manufacturingDbContext;
var ids = new[] {1, 2};
var manufacturingOrderList = context.ManufacturingOrders.Where(s => s.statusId == ids.Contains(s.statusId)).Select(o => o.lookupCode).ToList();
return manufacturingOrderList;
}
Here is the sql query where I need it translated to EF Code
select
o.lookupCode
from dbo.ManufacturingOrders o
where o.statusId in(1, 2)
the end result of this is to just get the lookupcode as you can see in my sql query, and that will display in my app. I looked other sites in google and also here and I could not find an exact answer of my question.
Should be something like:
var manufacturingOrderList = context.ManufacturingOrders
.Where(s => ids.Contains(s.statusId))
.Select(o => o.lookupCode)
.ToList();

PostgreSQL query not working in Yii2

I want to execute query in my yii2 application. I'm using PostgreSQl. There is a table called list inside the user schema. If I try to build any query it returns 1. My code is here:
$numUsers = Yii::$app->db->createCommand('
SELECT COUNT(*) FROM "user"."list"
')->execute();
Please show me my mistake in the query above.
This is not related to the DB type in Yii2 if you want the result of a single value you should use queryScalar() instead of execute()
$numUsers = Yii::$app->db->createCommand('
SELECT COUNT(*) FROM "user"."list" ')->queryScalar();

Sort a LINQ with another LINQ in MVC

Using SQL Server Management
Using MVC VS 2013 for Web
Being in a Controller
Here materialnumb it's a LINQ query that always return only one value.
Being the following...
var materialnumb = (from r in db.MaterialNumber
where r.MaterialNumber == 80254842
select r.MaterialNumber);
I have another LINQ query from a SQL view that involves several other tables with inner join statements and so on (which includes the previous table db.MaterialNumber) that goes like this:
var query = (from r in db.SQLViewFinalTable
where r.MaterialNumber == Convert.ToInt32(materialnumb.MaterialNumber)
select r
I want to sort all the materials by the retrieved material number from the first query but it drops the following error when I try to pass the query as a model for my View:
LINQ to Entities does not recognize the method 'Int32
ToInt32(System.String)' method, and this method cannot be translated
into a store expression.
I assume this is because the query is an object even if its has just one value so it can't be converted into a single Int32.
Even more, the query it's not being executed, it's just a query...
So, how can achieve my goal?
Additional information: I tried to convert the query outside the "final" query. It still doesn't work.
Additional information: This is just an example, the true query actually has several more other querys embedded and this other querys have also other querys in them, so I need a practical way.
Additional information: I have also tried to convert the query into a string and then again into an int.
Try this:
var materialnumb = (from r in db.MaterialNumber
where r.MaterialNumber == 80254842
select r.MaterialNumber).FirstOrDefault();
var query = from r in db.SQLViewFinalTable
where r.MaterialNumber == materialnumb
select r
But I can not get whay are you filtering by 80254842 and selecting the same value? You can do directly:
var query = from r in db.SQLViewFinalTable
where r.MaterialNumber == 80254842
select r

Resources