I'm working with two tables: CI_CLIENTRISK (SCD type 2)... and QB_INVOICES_HEADER (edmx screenshot).
They can be joined via ClientID. I want to essentially replicate this query:
SELECT a.ClientID,
MAX(b.InvoiceDt) AS MaxInvoiceDt
(omitted for brevity)
FROM CI_CLIENTRISKADJS a
INNER JOIN QB_INVOICES_HEADER b
ON a.ClientID = b.ClientID
WHERE a.IsActive = 1
GROUP BY a.ClientID
ORDER BY MaxInvoiceDt DESC
Here's what I have so far. It's not returning any records.
using (var db = new PLOGITENS01Entities())
{
var rvClientRiskAdjs = db.CI_CLIENTRISKADJS
.Take(50)
.Join(db.QB_INVOICES_HEADER,
a => a.ClientID,
b => b.ClientID,
(a, b) => new { Risk = a, Invoices = b })
.Where(a => a.Risk.IsActive == 1)
.OrderByDescending(o => o.Invoices.InvoiceDt)
.Select(c => new ClientRiskModel()
{
ClientRiskId = c.Risk.ClientRiskID,
ClientName = c.Risk.CI_CLIENTLIST.ClientName,
ClientId = c.Risk.ClientID,
ClientRiskAdjs = c.Risk.ClientRiskAdjs,
RecordValidStartDt = c.Risk.RecordValidStartDt,
RecordValidEnddt = c.Risk.RecordValidEnddt,
IsActive = c.Risk.IsActive
})
.ToList();
return View(new GridModel(rvClientRiskAdjs));
}
Try putting your .Take(50) method after your final .Select and before .ToList(). As it is, you are only taking the first 50 records of the first table and then joining from there. I'm assuming that there are no joins to the second table in the first 50 records of the first table; therefore, your result will have 0 records.
I stumbled across this solution from reading this post: https://stackoverflow.com/a/157919/1689144
var rvClientRiskAdjs = (from ri in db.CI_CLIENTRISKADJS
join qb in
(from qb in db.QB_INVOICES_HEADER
orderby qb.InvoiceDt ascending
group qb by qb.ClientID into grp
select new
{
InvoiceDt = grp.Max(s => s.InvoiceDt),
ClientID = grp.Key
})
on ri.ClientID equals qb.ClientID
orderby qb.InvoiceDt descending
where ri.IsActive == 1
select new ClientRiskModel()
{
ClientRiskId = ri.ClientRiskID,
ClientName = ri.CI_CLIENTLIST.ClientName,
ClientId = ri.ClientID,
ClientRiskAdjs = ri.ClientRiskAdjs,
RecordValidEnddt = ri.RecordValidEnddt,
RecordValidStartDt = ri.RecordValidStartDt
})
.ToList();
Related
I'm currently working to add Data to a GridView. The data comes from 2 tables that are on different databases. Currently I am able to populate the first entry, but it does not populate past that. here is the code:
void FillOrder(int inv)
{
var _ord = new OrdersContext();
var _pro = new ProductContext();
var qryOrder = (from o in _ord.OrderDetails
where o.InvNumberId == inv
select new
{
o.ProductID,
o.Quantity
}).ToList();
foreach (var order in qryOrder)
{
int prodID = order.ProductID;
int itemCount = qryOrder.Count;
var qryProducts = (from p in _pro.Products
where p.ProductID == prodID
select new
{
p.ProductID,
p.ProductName
}).ToList();
var results = (from t in qryOrder
join s in qryProducts
on t.ProductID equals prodID
select new
{
t.ProductID,
t.Quantity,
s.ProductName
}).ToList();
OrderItemList.DataSource = results;
OrderItemList.DataBind();
}
}
Can anyone help as to why it's only populating the first entry?
If the number of products involved is relatively small, (and since this query seems to be relate to one invoice, I would think that is true), then you can probably use something like the code below.
This is removing the loop, but the contains method will probably generate a SQL statement something like select ProductID, ProductName from products where productID in (,,,,,,) so may fail if the number of parameters is extremely large.
var _ord = new OrdersContext();
var _pro = new ProductContext();
var qryOrder = (from o in _ord.OrderDetails
where o.InvNumberId == inv
select new
{
o.ProductID,
o.Quantity
}).ToList();
// Get the productIDs
var productIDS = qryOrder.Select(o=>o.ProductID).Distinct().ToList();
// Get the details of the products used.
var qryProducts = (from p in _pro.Products
where productIDS.Contains(p.ProductID)
select new
{
p.ProductID,
p.ProductName
}).ToList();
// Combine the two in memory lists
var results = (from t in qryOrder
join s in qryProducts
on t.ProductID equals s.ProductID
select new
{
t.ProductID,
t.Quantity,
s.ProductName
}).ToList();
OrderItemList.DataSource = results;
OrderItemList.DataBind();
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);
Sorry if the title was confusing.
Currently I am practicing with Entity Framework and LINQ expressions and got stuck on this.
I have a table with columns:"Personal ID", "Name", "Surname", "Phone ID" and all values on Phone ID are unique. I would like to create another table in which there would be same columns except for last being "Phone Count" which shows how many phones are associated with same Person(Personal ID). I want the table to show only 3 first highest count rows.
Here is the code i've wrote to make table that i've described above.
using (var db = new PRDatabaseEntities())
{
var query = from a in db.Person
join t in db.Repairs on a.PID equals t.Repairman_PID
orderby a.PID
select new
{
a.PID,
a.Name,
a.Surname,
t.Phone_ID
};
}
You could try with following group by LINQ query:
// First, generate a linq query
var query = from a in Persons
join t in Repairs on a.PID equals t.Repairman_PID
group new { a, t } by new { a.PID, a.Name, a.Surname } into g
select new
{
PID = g.Key.PID,
Name = g.Key.Name,
Surname = g.Key.Surname,
PhoneCount = g.Count()
};
// Then order by PhoneCount descending and take top 3 items
var list = query.OrderByDescending(t => t.PhoneCount).Take(3).ToList();
Try this:
using (var db = new PRDatabaseEntities())
{
var query = db.Person
.GroupJoin(db.Repairs,
p => p.PID, r => r.PID,
(p, r) => new {
PID = p.PID,
Name = p.Name,
Surname = p.Surname,
Count = r.Count()
};
}
I have two tables User & Employee.
+-------Supervisor----------+
SupervisorId
Password
+---------------------+
+-------Employee----------+
EmployeeId
EmployeeSupervisorId
EmployeeName
+---------------------+
This is what I am doing so far
SupervisorName = db.Employee.Where(m => m.EmployeeSupervisorId == m.SupervisorId).Select(q => q.EmployeeName).ToList()
I am not understanding the concept of how I join my Employee table to itself so that I can get a list of Employee and their corresponding Supervisor Name
You can do the below
SupervisorName = db.Employee
.Join(db.Supervisor,
emp => emp.EmployeeSupervisorId,
sup => sup.SupervisorId,
(emp, sup)=> new {SupervisorName = emp.EmployeeName})
.Select(x=>x)
.ToList();
SupervisorName = db.Employee.
Join(db.Supervisoer, e => e.EmployeeSupervisorId, s => s.SupervisorId, (e, s) => new { Employee = e, Supervisor = s}.
ToList().
Select(e => e.EmployeeName).
ToList();
You can use a simple subquery like this
var result = db.Employee.Select(e => new
{
Employee = e,
SupervisorName = db.Employee
.Where(s => s.EmployeeId == e.EmployeeSupervisorId)
.Select(s => s.EmployeeName).FirstOrDefault()
}).ToList();
Note that if you have EmployeeSupervisorId defined as a foreign-key pointing back to EmployeeId, the Linq2Sql will automatically create a EmployeeSupervisor property (which would be an Employee object)
var list = from e in db.Employee
// where e.......
select new {
Name = e.EmployeeName,
Supervisor = e.EmployeeSupervisor.EmployeeName,
// otherdetails = e......
}
If you haven't defined the foreign key, you have to specify it explicitly in the query:
var list = from e in db.Employee
join s in db.Employee on e.EmployeeSupervisorId equal s.EmployeeId
// where e.......
select new {
Name = e.EmployeeName,
Supervisor = s.EmployeeName,
// otherdetails = e......
}
two different projects I want INNER JOIN statement to write out.
Include the second session of the results, but I can not get
using (ISession session = Con1.OpenSessiongeneral())
{
using (ISession session1 = Con2.OpenSessionsystem())
{
result = (from s in session.Query<AU_SalesTarget>()
join t in session.Query<AU_Terms>() on s.termId equals t.termId
join b in session1.Query<Branchs>() on s.branchId equals b.branchId
select new SalesTarget_Derogate
{
salesTargetId = s.salesTargetId,
mounth = t.month,
year = t.year,
calculateMethod = s.calculateMethod,
branchName = b.branchName
}).Skip(0).Take(50).ToList<SalesTarget_Derogate>();
}
}
list returns null
Im not sure why you get a null list, but you should use a store procedure if your SQL Server instance, support the join between different instances.
If is not supported, the solution is not elegant, you can try to get the data first, then use linq to join them like this:
using (ISession session = Con1.OpenSessiongeneral())
{
result = (from s in session.Query<AU_SalesTarget>()
join t in session.Query<AU_Terms>() on s.termId equals t.termId
select new
{
salesTargetId = s.salesTargetId,
mounth = t.month,
year = t.year,
calculateMethod = s.calculateMethod,
branchId = s.branchId
})
.Skip(0)
.Take(50)
.ToList();
}
var branchIds = result.Select(x => x.branchId)
.List();
Branchs bAlias = null;
IList<Branchs> branches = null;
using (ISession session1 = Con2.OpenSessionsystem())
{
branches = session1.QueryOver<Branchs>
.WhereRestrictionOn(x => x.branchId).IsIn(branchIds)
.Select(list => list
.Select(x => x.branchId).WithAlias(() => bAlias.branchId)
.Select(x => x.branchName).WithAlias(() => bAlias.branchName)
)
.TransformUsing(Transformers.AliasToBean<Branchs>())
.List<Branchs>();
}
result = result.Join(branches,
x => x.branchId,
x => x.branchId,
(x, y) => new SalesTarget_Derogate
{
salesTargetId = x.salesTargetId,
mounth = x.month,
year = x.year,
calculateMethod = x.calculateMethod,
branchName = y.branchName
}).ToList();