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.
Related
Here MyChildTable contains only id and the parent table contains id + name.
I have written a query to fetch the existing data from the table
await _dbContext.MyChildTable
.Where(c => c.CustomerId == **(select customerid from tableParent where customername= reqcustomername)**
Here i want to match customerId with the matching customer id from the second table ie tableParent.How to replace the query in to linq to get the proper record.select customerid from tableParent where customername= reqcustomername i want to replace this selection
I don't understand what you mean
so my maybe answer error
LINQ
using (entity entityData = new entity())
{
var checkqry2 = from T1 in entityData.MyChildTable.AsNoTracking()
join T2 in entityData.tableParent on
T1.CustomerId equals T2.customerid
where T1.customerid == "ID" && T2.customername == reqcustomername
group new { T2.customerid, T2.customername } by new { T1.customerid, T1.customername } into c
orderby c.Key.customerid
select new { customername=c.Key.customername,
customerid=c.Key.customerid,
};
}
you can try entity lambda
entity lambda
using (entity entityData = new entity())
{
var query1 = entityData.MyChildTable
.Join(entityData.tableParent , o => o.CustomerId , p => p.CustomerId , (o, p) => new
{
o.CustomerId,
p.customername,
}).Where(o => o.CustomerId == "123" && o.customername == "name").ToList();
}
Here I want to match customerId with the matching customer id from the
second table ie tableParent.How to replace the query in to linq to get
the proper record.select customerid from tableParent where
customername= reqcustomername i want to replace this selection
Well, lot of way around to handle this kind of scenario. Most easy and convenient way you could consider by using linq join or linq Enumerable which you can implement as following:
Sample Data:
var childList = new List<ChildTable>()
{
new ChildTable(){ Id =101,ChildName = "Child-A",CustomerId = 202},
new ChildTable(){ Id =102,ChildName = "Child-B",CustomerId = 203},
new ChildTable(){ Id =103,ChildName = "Child-C",CustomerId = 202},
new ChildTable(){ Id =104,ChildName = "Child-D",CustomerId = 204},
};
var parentList = new List<ParentTable>()
{
new ParentTable(){ Id =301,ParentName = "Parent-A",CustomerId = 202},
new ParentTable(){ Id =302,ParentName = "Parent-B",CustomerId = 202},
new ParentTable(){ Id =303,ParentName = "Parent-C",CustomerId = 203},
new ParentTable(){ Id =304,ParentName = "Parent-D",CustomerId = 205},
};
Linq Query:
Way One:
var findMatchedByCustId = from child in childList
where (from parent in parentList select parent.CustomerId)
.Contains(child.CustomerId)
select child;
Way Two:
var usingLinqJoin = (from parent in parentList
join child in childList on parent.CustomerId equals child.CustomerId
select parent).ToList().Distinct();
Output:
Note: If you need more information you could check our official document for Linq join and Linq Projction here.
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();
In al_jira_defect_out table i have Batch_Insert_Timestamp, AL_Defect_ID columns along with other columns.And In this table there will be duplicate AL_Defect_IDs with different Batch_Insert_Timestamp.
As per below code in linq i am getting all records which are Jira_Status == 0
var defects = (from d in db.al_jira_defect_out
join p in db.al_jira_ref_defect_project on d.Defect_Product_ID.ToString() equals p.al_product_id
join t in db.al_jira_ref_defect_type on d.Defect_Type_ID equals t.type
where d.Jira_Status == 0
select new Issue
{
fields = new CreateIssue
{
project = new Project
{
key = g.jira_project_key
},
issuetype = new Issuetype()
{
name = t.jira_equivalent
},
description = d.Defect_ShortDesc,
summary = d.Defect_DetailDesc,
versions = new List<Versions>
{
new Versions {name = d.Defect_Release_DetectedIn}
},
priority = new Priority
{
name = d.Defect_Severity_Name
},
customfield_10182 = d.AL_Defect_ID.ToString(),
}
}).Select().ToList();
i am getting record with AL_Defect_IDs duplicate.
But i required latest records[Max(d.Batch_Insert_Timestamp)] of each d.AL_Defect_ID with all required columns
can any one please help me to get linq query
If you group on AL_Defect_IDs, you can order by Batch_Insert_Timestamp and take the last (latest) one:
var defects = (from d in db.al_jira_defect_out
join p in db.al_jira_ref_defect_project on d.Defect_Product_ID.ToString() equals p.al_product_id
join t in db.al_jira_ref_defect_type on d.Defect_Type_ID equals t.type
where d.Jira_Status == 0
group new { d, p, t } on d.AL_Defect_ID into dptg
let dpt = (from dpt in dptg order by dpt.d.Batch_Insert_Timestamp select dpt).Last()
select new // ... whatever using dpt
Your sample code doesn't use p in the select, so you could leave it out of the grouping.
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 };
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();