Select Values from two tables using Linq - c#

Hi I know this has been asked plenty of times, I'm not getting it through my skull
How to select Values from several tables
I made these two Linq queries
First
r = (from d in db.stageManagers
where d.profileID == UserID && d.verticalID == VerticalID
select new StageModels()
{
UserId = d.profileID,
VerticalId = (int)d.verticalID,
VerticalStageID = d.stageID
}).FirstOrDefault();
Second
r = (from d in db.stageManagerVerticals
where d.ID == r.VerticalId
select new StageModels()
{
VerticalName = d.verticalName
}
).FirstOrDefault();
I want to make them one statement since they add data to one model and the tables they query have a Pk Fk relationship
In the first block d.verticalId is what I use to get the value(Name) in the secondblock, d.verticalId is primary key to stageManagerVerticals and foreign key in stageManager, How can i join these queries ?
I tried this:
r = (from d in db.stageManagers
join c in db.stageManagerVerticals on d.stageID equals c.ID
where d.profileID == UserID && d.verticalID == VerticalID
select new StageModels()
{
UserId = d.profileID,
VerticalId = (int)d.verticalID,
VerticalStageID = d.stageID;
VerticalName = c.verticalName
}
).FirstOrDefault();

try with JOIN in LINQ to select values from more than one table
eg:
var innerJoinQuery =
from category in categories
join prod in products on category.ID equals prod.CategoryID
select new { ProductName = prod.Name, Category = category.Name };

var leftOuterJoin=(c in categories
join p in products on c.ID equals p.CategoryID into t
from temp in t.DefaultIfEmpty()
select new { ProductName = p.Name, Category = c.Name }
).ToList();

You can utilize the Navigational Properties,
var r = db.stageManagers.Where(x => x.profileID == UserID && x.verticalID == VerticalID).
Select(
d => new StageModels() {
UserID = d.profileID,
VerticalID = (int)d.verticalID,
VerticalStageID = d.stageID,
VerticalName = d.stageManagerVertical.verticalName
}
).FirstOrDefault();

Related

GridView Only populating 1 result

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();

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 pull one column from second table in Linq query with join

I have the following linq query that works fine, but I am wanting to pull one column (CompanyId) from context.Emps into the results along with the results from context.BillingProfiles. How would I modify the select (select prof) below to include said column?
var query = (from prof in context.BillingProfiles
join emp in context.Emps on prof.ID equals emp.ID
join grp in context.BillingGroups on prof.GroupID equals grp.GroupID
where (prof.EndDate == null) && (grp.System == "sysGrp") && (prof.ID == id)
select prof).Distinct()
.Select(x => new OpId()
{
id = x.ID,
GroupId = x.GroupID,
OpId = x.OpID,
StartDate = x.StartDate,
EndDate = x.EndDate,
AddedOn = x.AddedOn,
AddedBy = x.AddedBy,
RemovedOn = x.RemovedOn,
RemovedBy = x.RemovedBy,
Prodid = x.ProdID,
});
Thanks
Project an anonymous object containing those too:
var query = from prof in context.BillingProfiles
join emp in context.Emps on prof.ID equals emp.ID
join grp in context.BillingGroups on prof.GroupID equals grp.GroupID
where prof.EndDate == null && prof.ID == id && grp.System == "sysGrp"
select new { prof, emp.CompanyId, grp };

EF 6 dynamically create inner join

I am using Entity framework 6.
I need to pass in a two table names and create a LINQ query that I will be able to use to populate a Kendo Datasource.
This is the code that I am currently trying to change to dynamic.
var entryPoint = (from pd in db.Employees
join od in db.MessageEmployees on pd.EmpID equals od.EmployeeID into t
from rt in t.DefaultIfEmpty()
where pd.Class == clssID && pd.IsInactive == 0
orderby pd.Class
select new
{
ClassID = pd.Class,
pd.FirstName,
pd.LastName,
pd.EmpID,
pd.EmployeeID,
EmpMessageID = rt.EmployeeID
});
//IQueryable<Employee> emps = db.Employees;
DataSourceResult result = entryPoint.ToDataSourceResult(request, empl => new HierachyEmployee
{
ClassID = empl.ClassID,
FirstName = empl.FirstName,
LastName = empl.LastName,
EmpID = empl.EmpID,
IsChecked = empl.EmpMessageID != null
});
return Json(result);
I need db.MessageEmployees and db.Employees to be dynamic. Thank you in advance for any help.

Syntax for "and" and distinct operation in entity framework?

I want to display the records whose accountid, id are matching and also display distinct records.
var result = from a in cxt.tblInventoryProducts
where a.aid == accID && a.id == id
select new
{
a.productType,
a.productName
};
Thanks in advance
Something like
var result = from a in cxt.tblInventoryProducts
where a.aid == accID && a.id == id
group a by new { a.productType, a.productName } into grp
select new
{
grp.Key.productType,
grp.Key.productName
};

Categories

Resources