how to write a nested Sql query in Linq [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
so i have this query in sql:
select (select ConfigItemDescripcion from SGRC_ConfigItem where ConfigId = 'SEGM' and ConfigItemId = SegmentoId) Segmento,
(select ConfigItemDescripcion from SGRC_ConfigItem where ConfigId = 'MRCA' and ConfigItemId = MarcaId) Marca,
Producto,
Familia
from sgrc_emisor
where EmisorCuenta = '3702406435'
I want to write the same query in a linq expression or a lambda expression.
Thanks for the help in advance

Finally i manage to come up with the query in linq, dont know how to do it in lambda, but it works fine.
var obj = (from emisor in _context.DbSetEmisores
where emisor.EmisorCuenta == cuenta
select new EmisorDto
{
Segmento =
((from itemConf in _context.ItemsDeConfiguracion
where itemConf.ConfigID == "SEGM" && itemConf.ConfigItemID == emisor.SegmentoId
select new { itemConf.ConfigItemDescripcion }).FirstOrDefault().ConfigItemDescripcion),
Marca =
((from itemConf in _context.ItemsDeConfiguracion
where itemConf.ConfigID == "MRCA" && itemConf.ConfigItemID == emisor.MarcaId
select new { itemConf.ConfigItemDescripcion }).FirstOrDefault().ConfigItemDescripcion),
Producto = emisor.Producto,
Familia = emisor.Familia,
SegmentoId = emisor.SegmentoId,
MarcaId = emisor.MarcaId,
}).FirstOrDefault();

When using LINQ you can use either Query syntax as shown in the LINQ below (If you are familiar with SQL then this looks more natural).
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/query-syntax-and-method-syntax-in-linq
The other option is to use Method syntax, and below is a short example. This allows for chaining of methods, biggest thing to keep in mind is "var" should be used, the return type is dynamic and the compiler will help you out a lot if you just use "var"
var items = _list.Where(x => x.Attribute1 == "NextField")
.Where(x => x.Attribute2 == "Something else");
Other things that hangs folks up sometimes is LINQ uses "delayed execution"

Related

Inner Join LINQ Without making a New Model [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I'm working with LINQ and I need to do a inner join. This is my code:
var requests =
(from request in db.Request
join estatus in db.typesStatus
on request.fkStatus equals estatus.idStatus
where request.fkStatus == status && DbFunctions.TruncateTime(request.dateRquest) == DbFunctions.TruncateTime(fecha)
select new { request = request, estatus = estatus.status, nombre = (String)UserAccessRequest.checkUserAsync(request.wiwMakeRequest, "name").Result })
.ToList();
I'm trying to call a method inside my LINQ query. This one calls an API and returns a string but I recieved the next error:
LINQ to Entities does not recognize the method
'System.Threading.Tasks.Task`1[System.Object]
checkUserAsync(System.String, System.String)' method, and this method
cannot be translated into a store expression.
Is any way to make the LINQ query without making a model to the result of this LINQ query?
Just call your method after LINQ query loaded data into memory:
var requests =
(from request in db.Request
join estatus in db.typesStatus
on request.fkStatus equals estatus.idStatus
where request.fkStatus == status && DbFunctions.TruncateTime(request.dateRquest) == DbFunctions.TruncateTime(fecha)
select new { request = request, estatus = estatus.status })
.ToList()
.Select(i => new { i.request, i.estatus, nombre = (String)UserAccessRequest.checkUserAsync(i.request.wiwMakeRequest, "name").Result })
.ToList()

how to use joining with LinQ To Entity [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have this code
var value = (from dc in _context.ContractDetails
where dc.EmployeeID == id
select dc.Amount);
return value;
}
is it acceptable to do Value.Sum();
You want to return the sum it looks like. Instead of having query be a decimal, just let it be what it wants (var, it's really IEnumerable<decimal>). Then you can return an aggregate on that. Sum for example
var query = from emp in Employees
join cd in ContractDetails
on emp.EmployeeID equals cd.EmployeeID
where cd.EmployeeID == id
select cd.Amount;
return query.Sum();
If this is all it does, then I also feel like you don't need to join at all, and it would be simpler to do
var query = from cd in ContractDetails
where cd.EmployeeID == id
select cd.Amount;
return query.Sum();
... unless you were using the join to test for the existence of an employee in the Employee table as a condition.
Your linq statement results in an IQueryable<Amount>, you would need to take that result and call Sum() on it to get the result you're seeking.
First, isn't there a navigation property you can use (i.e. Employee.ContracteDetails) instead of manually joining the two sets? For example,
var sum = _context.Employee
.Where( e => e.Id == id )
.Select( e => e.ContractDetails.Sum( cd => cd.Amount ) )
.SingleOrDefault();
Second, you're not using any information you need from Employee, even your where clause references ContractDetails alone; why start your query there? Work with _context.ContractDetails instead:
var sum = _context.ContractDetails
.Where( cd => cd.EmployeeId == id )
.Sum( cd => cd.Amount );

How to write the below SQL query to LINQ query in C#? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
How to convert normal SQL to LINQ query? Is there tools that can do that?? Online Tools
Have you tried something like this (a few joins omitted for brevity):
var result = from s in TooltipsLanguage
join c in TooltipsLanguageSection on s.Id equals c.IdLanguage
join p in TooltipsSection on c.IdSection equals p.Id
join ...
select new MyDestinationObject()
{
Id = s.BusinessEntityID,
Language = s.Language,
IdLanguage = c.IdLanguage,
...
};
This meight be help you.
var temp= edbContext.TooltipsLanguage.select(
c=> new {
TooltipsLanguage.Id,
TooltipsLanguage.Language,
TooltipsLanguage.TooltipsLanguageSection.Id,
TooltipsLanguage.TooltipsLanguageSection.IdLanguage,
TooltipsLanguage.TooltipsLanguageSection.IdSection,
TooltipsLanguage.TooltipsLanguageSection.TooltipsSection.Id,
TooltipsLanguage.TooltipsLanguageSection.TooltipsSection.Section,
TooltipsLanguage.TooltipsLanguageSection.TooltipsSection.Section.TooltipsItem.Id,
TooltipsLanguage.TooltipsLanguageSection.TooltipsSection.Section.TooltipsItem.IdItem,
TooltipsLanguage.TooltipsLanguageSection.TooltipsSection.Section.TooltipsItem.TooltipsItemText.Id,
TooltipsLanguage.TooltipsLanguageSection.TooltipsSection.Section.TooltipsItem.TooltipsItemText.IdItem,
TooltipsLanguage.TooltipsLanguageSection.TooltipsSection.Section.TooltipsItem.TooltipsItemText.IdText,
TooltipsLanguage.TooltipsLanguageSection.TooltipsSection.Section.TooltipsItem.TooltipsItemText.TooltipsText.Id,
TooltipsLanguage.TooltipsLanguageSection.TooltipsSection.Section.TooltipsItem.TooltipsItemText.TooltipsText.Texts});

Convert SQL statement to LINQ with case condition [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have a problem with converting a native select statement with CASE statement using LINQ.
This is the native SQL which is working in SQL Server :
select
v.vehl_ContainerNo as cont_name, v.vehl_Name,
v.vehl_drivername, v.vehl_entrancedate, v.vehl_customsdec,
c.Capt_AR as VehicleState,
case
when v.vehl_rampid is null
then ''
else (select ramp_Name
from Ramp
where ramp_RampID = v.vehl_rampid)
end as cont_rampid
from
Vehicle v, Custom_Captions c
where
v.vehl_state = c.Capt_Code
and c.Capt_Family = 'vehl_state'
and v.vehl_ClearanceCompany = 471
I want to get the ramp_name:
if vehl_rampid is null then return an empty string
else do another select statement to get the ramp_name from the ramp table where vehl_rampid equals ramp_rampid.
when i use the following linq statement:
//List<qryRslt> query = (from v in db.Vehicles
// join cus in db.Custom_Captions on v.vehl_state equals cus.Capt_Code
// join ram in db.Ramps on v.vehl_rampid equals ram.ramp_RampID
// where
// cus.Capt_Family == "vehl_state" && v.vehl_Deleted == null && v.vehl_ClearanceCompany == p.pusr_CompanyId
// select new qryRslt
// {
// vehl_ContainerNo = v.vehl_ContainerNo,
// vehl_Name = v.vehl_Name,
// vehl_drivername=v.vehl_drivername,
// vehl_entrancedate=v.vehl_entrancedate,
// vehl_customsdec=v.vehl_customsdec,
// VehicleState=v.vehl_state,
// cont_rampid=v.vehl_rampid==null?" ":ram.ramp_Name
// }).ToList();
it gives me an unexpected result that differs from native sql statement written in sql server
How can I implement sql statement with another sql in case statement?
It depends what you returning. Let's assume you are trying to return class: MyClass
Then LINQ would looks something like:
List<MyClass> result = (from c in Vehicle
from x in Custom_Captions
join z in Ramp on c.vehl_rampId equals z.ramp_RampID
where c.vehl_state == x.Capt_Code
&& x.Capt_Family == 'vehl_state'
&& c.vehl_ClearanceCompany == 471
select new MyClass{
prop1 = c.vehl_rampid is null ? "" : z.ramp_Name
}).ToList();
Above code is using Object Initialiser to define object by filling it's all properties.

linq convert query syntax to method syntax [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
How can I convert this query syntax to method syntax in linq:
return (from x in db.Table1
join y in db.Table1 on x.ID equals y.ID - 1
where Convert.ToInt32(y.ID) >= Convert.ToInt32(x.ID)
orderby x.Name
select x).Distinct();
Which approach is better? I like this query approach better but I was asked to work with method syntax which looks too bloated to me.
var results = db.Table1.Join
(
db.Table1,
x=>x.ID,
x=>x.ID - 1,
(x,y)=>new{OuterTable = x, xid = x.ID, yid = y.ID}
)
.Where(x=>Convert.ToInt32(x.yid ) >= Convert.ToInt32(x.xid))
.Select(x=>x.OuterTable)
.OrderBy(x=>x.Name)
.Distinct();

Categories

Resources