I want to filter my LINQ query based on an included table but am having some trouble.
Here is the original statement, which works:
return
this.ObjectContext.People.
Include("Careers").
Include("Careers.Titles").
Include("Careers.Titles.Salaries");
Now I'm trying to filter on Careers using projected filtering but am having trouble. It compiles but it leaves out the Titles and Salaries tables, which causes runtime errors, and I can't seem to add those tables back in:
var query1 = (
from c in
this.ObjectContext.People.
Include("Careers").
Include("Careers.Titles").
Include("Careers.Titles.Salaries")
select new
{
c,
Careers = from Careers in c.Careers
where Careers.IsActive == true
select Careers
});
var query = query1.AsEnumerable().Select(m => m.c);
return query.AsQueryable();
How can I include the titles and salaries tables in the filtered query?
You can simplify your query considerably, which should resolve your issue. I'm assuming that you want all people with at least 1 active career:
var query =
from c in
this.ObjectContext.People.
Include("Careers").
Include("Careers.Titles").
Include("Careers.Titles.Salaries")
where c.Careers.Any(c => c.IsActive);
return query;
I would try something like,
var query = from p in ObjectContext.People
join c in ObjectContext.Careers on p equals c.Person
where c.IsActive
select p;
Related
I am using below code to join two tables based on officeId field. Its retuning 0 records.
IQueryable<Usage> usages = this.context.Usage;
usages = usages.Where(usage => usage.OfficeId == officeId);
var agencyList = this.context.Agencies.ToList();
var usage = usages.ToList();
var query = usage.Join(agencyList,
r => r.OfficeId,
a => a.OfficeId,
(r, a) => new UsageAgencyApiModel () {
Id = r.Id,
Product = r.Product,
Chain = a.Chain,
Name = a.Name
}).ToList();
I have 1000+ records in agencies table and 26 records in usage table.
I am expecting 26 records as a result with chain and name colums attached to result from agency table.
Its not returning anything. I am new to .net please guide me if I am missing anything
EDIT
#Tim Schmelter's solution works fine if I get both table context while executing join. But I need to add filter on top of usage table before applying join
IQueryable<Usage> usages = this.context.Usage;
usages = usages.Where(usage => usage.OfficeId == officeId);
var query = from a in usages
// works with this.context.usages instead of usages
join u in this.context.Agencies on a.OfficeId equals u.OfficeId
select new
{
Id = a.Id,
Product = a.Product,
Chain = u.Chain,
Name = u.Name
};
return query.ToList();
Attaching screenshot here
same join query works fine with in memory data as you see below
Both ways works fine if I add in memory datasource or both datasource directly. But not working if I add filter on usages based on officeId before applying join query
One problem ist that you load all into memory first(ToList()).
With joins i prefer query syntax, it is less verbose:
var query = from a in this.context.Agencies
join u in this.context.Usage on a.OfficeId equals u.OfficeId
select new UsageAgencyApiModel()
{
Id = u.Id,
Product = u.Product,
Chain = a.Chain,
Name = a.Name
};
List<UsageAgencyApiModel> resultList = query.ToList();
Edit: You should be able to apply the Where after the Join. If you still don't get records there are no matching:
var query = from a in this.context.Agencies
join u in this.context.Usage on a.OfficeId equals u.OfficeId
where u.OfficeId == officeId
select new UsageAgencyApiModel{ ... };
The following code can help to get the output based on the ID value.
Of course, I wrote with Lambda.
var officeId = 1;
var query = context.Agencies // your starting point - table in the "from" statement
.Join(database.context.Usage, // the source table of the inner join
agency => agency.OfficeId, // Select the primary key (the first part of the "on" clause in an sql "join" statement)
usage => usage.OfficeId , // Select the foreign key (the second part of the "on" clause)
(agency, usage) => new {Agency = agency, Usage = usage }) // selection
.Where(x => x.Agency.OfficeId == id); // where statement
I am trying to write a LINQ query equivalent to below SQL
SELECT DISTINCT m.*,rm.RoleId FROM dbo.Menu m
INNER JOIN dbo.RoleMenu rm on m.Id=rm.MenuId
INNER JOIN dbo.RoleUser ru on rm.RoleId=ru.RoleId
WHERE ru.UserName='dd#dd.com' and m.Url='/dashboard#/pm'
I came with the below query which is not returning the expected output
var auth = _context.RoleUsers.Where(
x => x.Role.MenuRoles.FirstOrDefault().Menu.Url == pagePermissions.Url
&& x.UserName == pagePermissions.UserName).Count()
May I know a better way to do this?
Your sql looks at all the menus related to a role user, but your Linq is only looking at the first one. I think you want x.Role.MenuRoles.Any(mr => mr.Menu.Url == pagePermissions.Url). But then you're also doing a Count on the matching users instead of selecting the menus that match that url. A closer translation would be.
var results = (from m in _context.Menus
from rm in m.RoleMenus
from ru in rm.RoleUsers
where m.Url == pagePermissions.Url
&& u.UserName == pagePermissions.UserName
select new { Menu = m, rm.RoleId }).Distinct();
You may have to adjust some of the navigation properties as I was just guessing at them. They usually are pluralizations of the tables, but I see in your Linq that you have MenuRoles instead of RoleMenus.
How can I rewrite the following Linq query into normal T-SQL?
var list = (from t in context.ParentTable
where t.ChildRecords.Count == t.ChildRecord.Count( c => c.BooleanColumn )
select t).ToList();
Thanks in advance...
Something like this, but you'll need to determine the relationship between the ParentTable and ChildRecord tables to make it work, I'm just guessing at the cr.ParentTableId = pt.ParentTableId part.
select pt.*
from ParentTable pt
where not exists
(select 1
from ChildRecord cr
where cr.ParentTableId = pt.ParentTableId
and cr.BooleanColumn = 0)
On a side note the Linq could be changed to the following instead.
var list = (from t in context.ParentTable
where t.ChildRecords.All(c => c.BooleanColumn)
select t).ToList();
i have something like this now, which only searches for 1 LabID
List<Expense> lstExpenses = (from l in ctx.Expenses
where l.datLab.Lab_ID == labID
select l).ToList<Expense>();
how do i return all results where Lab_ID is in a dictionary i have:
the followin functions returns a dictionary value: report.GetLabChildren(labID, "All"); is in <short>,<string> format. i only want to search on the <short>
If you want to do the filtering in linq to objects:
var query = ctx.Expenses.AsEnumerable()
.Where(expense => dictionary.ContainsKey(espense.Lab_Id));
If you want something that can be translated to the database:
var ids = dictionary.Keys.ToList();
var query = ctx.Expenses
.Where(expense => ids.Contains(expense.Lab_Id));
Note this will only work if you have less than a few thousand keys in your dictionary, as it is translated to a SQL IN clause. If you have more than that either upload them to a temporary table and join the two tables, or pull the entire Expenses table and use the linq to objects version.
List<Expense> lstExpenses = (from l in ctx.Expenses
where report.GetLabChildren(labID, "All").Keys.Contains(i.Lab_ID)
select l).ToList<Expense>();
I'm not 100% sure what you're asking about, but looks like you're looking for ContainsKey method:
var values = report.GetLabChildren(labID, "All");
List<Expense> lstExpenses = (from l in ctx.Expenses
where values.ContainsKey(l.datLab.Lab_ID)
select l).ToList<Expense>();
I'm not sure, but there is a chance that it won't work with LINQ to Entities. Use following if it happens:
List<Expense> lstExpenses = (from l in ctx.Expenses
where values.Keys.Contains(l.datLab.Lab_ID)
select l).ToList<Expense>();
I have a table, lets call it Record. Containing:
ID (int) | CustID (int) | Time (datetime) | Data (varchar)
I need the latest (most recent) record for each customer:
SQL
select * from record as i group by i.custid having max(id);
LINQ version 1
dgvLatestDistinctRec.DataSource = from g in ee.Records
group g by g.CustID into grp
select grp.LastOrDefault();
This throws an error:
System.NotSupportedException was unhandled by user code Message=LINQ
to Entities does not recognize the method 'Faizan_Kazi_Utils.Record
LastOrDefault[Record
](System.Collections.Generic.IEnumerable`1[Faizan_Kazi_Utils.Record
])' method, and this method cannot be translated into a store
expression. Source=System.Data.Entity
LINQ version 2
var list = (from g in ee.Records
group g by g.CustID into grp
select grp).ToList();
Record[] list2 = (from grp in list
select grp.LastOrDefault()).ToArray();
dgvLatestDistinctRec.DataSource = list2;
This works, but is inefficient because it loads ALL records from the database into memory and then extracts just the last (most recent member) of each group.
Is there any LINQ solution that approaches the efficiency and readability of the mentioned SQL solution?
Update:
var results = (from rec in Record group rec by rec.CustID into grp
select new
{
CustID = grp.Key,
ID = grp.OrderByDescending(r => r.ID).Select(x => x.ID).FirstOrDefault(),
Data = grp.OrderByDescending(r => r.ID).Select(x => x.Data).FirstOrDefault()
}
);
So I made a test table and wrote a Linq -> SQL Query that will do exactly what you need. Take a look at this and let me know what you think. Only thing to keep in mind if this query is scaled I believe it will run a query to the DB for each and every CustID record after the grouping in the select new. The only way to be sure would be to run SQL Tracer when you run the query for info on that go here .. http://www.foliotek.com/devblog/tuning-sql-server-for-programmers/
Original:
Could you do something like this? from g in ee.Records where g.CustID == (from x in ee.Records where (g.CustID == x.CustID) && (g.ID == x.Max(ID)).Select(r => r.CustID))
That's all pseudo code but hopefully you get the idea.
I'm probably too late to help with your problem, but I had a similar issue and was able to get the desired results with a query like this:
from g in ee.Records
group g by g.CustID into grp
from last in (from custRec in grp where custRec.Id == grp.Max(cr => cr.Id) select custRec)
select last
What if you replace LastOrDefault() with simple Last()?
(Yes, you will have to check your records table isn't empty)
Because I can't see a way how MySQL can return you "Default" group. This is not the thing that can be simply translated to SQL.
I think grp.LastOrDefault(), a C# function, is something that SQL doesn't know about. LINQ turns your query into an SQL query for your db server to understand. You might want to try and create an stored procedure instead, or another way to filter out what your looking for.
The reason your second query works is because the LINQ to SQL returns a list and then you do a LINQ query (to filter out what you need) on a C# list, which implements the IEnumerable/IQueryable interfaces and understands the grp.LastOrDefault().
I had another idea:
// Get a list of all the id's i need by:
// grouping by CustID, and then selecting Max ID from each group.
var distinctLatest = (from x in ee.Records
group x by x.CustID into grp
select grp.Max(g => g.id)).ToArray();
// List<Record> result = new List<Record>();
//now we can retrieve individual records using the ID's retrieved above
// foreach (int i in distinctLatest)
// {
// var res = from g in ee.Records where g.id == i select g;
// var arr = res.ToArray();
// result.Add(res.First());
// }
// alternate version of foreach
dgvLatestDistinctRec.DataSource = from g in ee.Records
join i in distinctLatest
on g.id equals i
select g;