Sql Join Subquery output in Linq - c#

I'm write some SQL query with join and sub query i want convert into linq
select a.CampaignId, a.ImagePath,(select Count(a1.CampaignId) from INN_Customers_Campaigns_Images a1 where a1.CampaignId = a.CampaignId)ImageCount from INN_Customers_Campaigns_Images a
inner join INN_Customers_Gallary b On b.CampaignId = a.CampaignId and a.CreatedBy = b.CustomerId

You can use let clause for your sub query
var result = from a in context.INN_Customers_Campaigns_Images
join b in context.INN_Customers_Gallary on new { a.CampaignId , a.CreatedBy } equals new { b.CampaignId , b.CustomerId }
let imageCount = context.INN_Customers_Campaigns_Images.Where(a1 => a1.CampaignId == a.CampaignId).Count()
select new
{
a.CampaignId,
a.ImagePath
ImageCount = imageCount
}

Related

Particular Query in Linq It does not perform the same thing as an inner join in SQL Server

This query is being carried out to take the zone and category names from the respective Product-related tables.
SELECT
Categoria.NombreCategoria,
Zona.ZonaGrupo,
p.NombreProducto,
p.ProductoTiene,
p.RealizadosEvento,
p.FechaInicial,
p.FechaFin
FROM
Productos p
INNER JOIN
Categoria ON p.CategoriaId = Categoria.Id
INNER JOIN
Zona ON p.ZonaId = Zona.ZonaId
The result of the SQL query returns the 1000 records that the products table must have with their zones and categories.
When doing the following in linq, it returns only 8 records ...
IQueryable<ProductosViewModel> ProductosMaped =
from p in Db.Productos
join g in Db.Zona on p.ZonaId equals g.ZonaId
join acr in Db.Categoria on p.CategoriaId equals acr.Id
select new ProductosViewModel
{
Categoria = acr.NombreCategoria,
ZonaGrupo = g.ZonaGrupo,
NombreProducto = p.NombreProducto,
ProductoTiene = p.ProductoTiene,
RealizadosEvento = p.RealizadosEvento,
FechaInicial = p.FechaInicial,
FechaFin = p.FechaFin,
};
I only need to link these 2 tables so that list only shows me CategoryName and ZoneName or Group Zone.
Better idea: Use Include with navigation properties:
List<ProductosViewModel> list = await this.Db.Productos
.Include( p => p.Zona )
.Include( p => p.Categoria )
.Where( p => p.Categoria != null && p.Zona != null ) // <-- This step may be optional depending on your database.
.Select( p => new ProductosViewModel
{
Categoria = p.Categoria.NombreCategoria,
ZonaGrupo = p.Zona.ZonaGrupo,
NombreProducto = p.NombreProducto,
ProductoTiene = p.ProductoTiene,
RealizadosEvento = p.RealizadosEvento,
FechaInicial = p.FechaInicial,
FechaFin = p.FechaFin,
} )
.ToListAsync()
.ConfigureAwait(false);

How to convert to Linq

How to convert the following query into linq
SELECT
a.ProductId,
a.Name,
a.Description,
b.Quoteid,
b.Productid,
b.Quantity,
b.OriginalPrice
FROM
Products AS a
LEFT JOIN
QuoteDtails AS b
ON a.ProductId = b.ProductId
AND b.QuoteId = 200;
Don't know where to add the AND condition.
Thanks and regards
You can try this linq if you want to write LEFT JOIN of linq, you need to add
into [temp collection] from [Left join talbe collection] in [temp collection].DefaultIfEmpty()
after Linq join
look like this.
from ss in Products
join aa in QuoteDtails
on ss.ProductId equals aa.ProductId into temp
from ds in temp.DefaultIfEmpty()
where ds.QuoteId = 200
select new
{
ProductId_P = ss.ProductId,
Name = ss.Name,
Description = ss.Description,
Quoteid = ds.Quoteid,
Productid_Q = ds.Productid,
Quantity = ds.Quantity,
OriginalPrice = ds.OriginalPrice
}
You can add AND condition in your LINQ query like this :
var res = from p in products
join q in quoteDtails on new { Criteria1 = p.ProductID, Criteria2 = 200 } equals new { Criteria1 = q.Productid, Criteria2 = q.Quoteid }
select new
{
ProductId_P = p.ProductID,
Name = p.Name,
Description = p.Description,
Quoteid = q.Quoteid,
Productid_Q = q.Productid,
Quantity = q.Quantity,
OriginalPrice = q.OriginalPrice
};

Left join and case clause LINQ in Entity Framework

I am needing to make a left join and also use the select operator case.
My LINQ basic is this and works:
resultado.Dados =
(
from a in db.AgendaHorario
join b in db.Agenda on a.AgendaID equals b.AgendaID
join c in db.Profissional on a.ProfissionalID equals c.ProfissionalID into d
from e in d.DefaultIfEmpty()
select new
{
id = a.AgendaHorarioID,
Medico = e.Identificacao
});
But I must add a new field and it should be formatted, then my LINQ looked like this:
resultado.Dados =
(
from a in db.AgendaHorario
join b in db.Agenda on a.AgendaID equals b.AgendaID
join c in db.Profissional on a.ProfissionalID equals c.ProfissionalID into d
from e in d.DefaultIfEmpty()
select new
{
id = a.AgendaHorarioID,
Medico = e.Identificacao,
start = a.Horario.ToString("yyyy-MM-dd HH:mm:ss")
}
);
This error happens:
LINQ to Entities does not recognize the method 'System.String ToString(System.String)' method, and this method cannot be translated into a store expression.
If you add the ToList() or AsEnumerable() in db.AgendaHorario.ToList() and db.Agenda.ToList() and db.Profissional.ToList() error that appears is:
Object reference not set to an instance of an object.
What should I do to have a left join with case and fields and formatted fields
Try this:
resultado.Dados =
(
from a in db.AgendaHorario
join b in db.Agenda on a.AgendaID equals b.AgendaID
join c in db.Profissional on a.ProfissionalID equals c.ProfissionalID into d
from e in d.DefaultIfEmpty()
select new
{
id = a.AgendaHorarioID,
Medico = e.Identificacao,
start = a.Horario
}).AsEnumerable().Select(x => new
{
id = x.id,
Medico = x.Medico,
start = x.start.ToString("yyyy-MM-dd HH:mm:ss")
}
);
try to set the string in a variable then assign it to your query like this:
var myValue = Horario.ToString("yyyy-MM-dd HH:mm:ss");
resultado.Dados = (
from a in db.AgendaHorario
join b in db.Agenda on a.AgendaID equals b.AgendaID
join c in db.Profissional on a.ProfissionalID equals c.ProfissionalID into d
from e in d.DefaultIfEmpty()
select new
{
id = a.AgendaHorarioID,
Medico = e.Identificacao,
start = myValue
} );

Join in LINQ Query

I am using Following LINQ query to fetch data from datatable
var callBetweenNodesDetail = from r in dtRowCallBetweenNodes.AsEnumerable()
where ((r.Field<string>("F1") == VerSelected1) && (r.Field<string>("F2") == VerSelected2))
select r;
Now i wanna join another datatable dtRowFile that contains two fields "Name" and "F2" where field "F2" is to be matched with "F10" in datatable dtRowCallBetweenNodes to get "Name" in resultset
Would this help:
var ret = from p in Table1.AsEnumerable()
join q in Table2.AsEnumerable() on p.Field<int>("ID") equals q.Field<int>("ID") into UP
from q in UP.DefaultIfEmpty()
select new
{
ID = p.Field<int>("ID"),
Type = p.Field<string>("Type"),
Part = q.Field<int>("Part"),
Quantity = q.Field<int>("Quantity")
};
var rowFileNames = from r1 in dtRowCallBetweenNodes.AsEnumerable()
join r2 in dtRowFile.AsEnumerable()
on r1.Field<string>("F10") equals r2.Field<string>("F2")
where r1.Field<string>("F1") == VerSelected1
&& r1.Field<string>("F2") == VerSelected2
select r2.Field<string>("Name");
Cross-Table Queries (LINQ to DataSet)

Linq query with a Conditional WHERE Clause

I am new to LINQ so apologises upfront
I have the following Linq query :-
var OrdersByBranches =
from a in AllOrders
join b in AllBranchKeys
on a.BranchKey equals b.BranchKey
orderby a.Date
group a by new { a.Date, a.paymentMethod } into BranchOrderGrouped
select new
{
BranchOrderGrouped.Key.Date,
CurrencyAmount = BranchOrderGrouped.Sum(a =>
a.CurrencyAmount),
BranchOrderGrouped.Key.paymentMethod
};
I need to include a where clause in the above query ... only if a variable called
BranchKeySelected is ""
I have tried using an If Else statement and have the same above query duplicated with
one containing a where clause and one NOT. ...But When I do this .. then OrdersByBranches
is NOT available outside of the IF Statement
Would be grateful for any help
Regards
Ghost
var OrdersByBranches =
from a in AllOrders
join b in AllBranchKeys on a.BranchKey equals b.BranchKey
orderby a.Date
group a by new { a.Date, a.paymentMethod } into BranchOrderGrouped
select new {
BranchOrderGrouped.Key.Date,
CurrencyAmount = BranchOrderGrouped.Sum(a => a.CurrencyAmount),
BranchOrderGrouped.Key.paymentMethod
};
if(string.IsNullOrEmpty(BranchKeySelected ))
{
OrdersByBranches = OrdersByBranches.Where(/*blbabla*/);
}
return OrdersByBranches;
Try (and my linq is not polished)
var OrdersByBranches = from a in AllOrders
join b in AllBranchKeys on a.BranchKey equals b.BranchKey
where b.BranchKeySelected.Contains("")
orderby a.Date group a by new
{
a.Date,
a.paymentMethod
}
into BranchOrderGrouped
select new
{
BranchOrderGrouped.Key.Date,
CurrencyAmount = BranchOrderGrouped.Sum(a => a.CurrencyAmount),
BranchOrderGrouped.Key.paymentMethod
};

Categories

Resources