EF6 How to query where children contains all values of a list - linq

Say I have a document table, with doc_id (PK) and doc_name fields, a category table with cat_id (PK) and cat_name fields, and a document_categories table with doc_id (PK, FK) and cat_id (PK, FK) fields, so I can attribute one or many categories to each document.
I have generated a model with EF6 in "Database first" mode, which gives me two entities: document and category, each containing a field which is a collection of children.
document contains a categories field which lists the categories of the document, and vice-versa in the category entity.
Now, I want to query all documents that contain category 1 AND category 2.
Let's say the database contains the following documents:
Doc A: Categories 1, 3
Doc B: Categories 1, 2
Doc C: Categories 1
Doc D: Categories 1, 2, 3
My query should return docs B and D.
How can I achieve that with EF6 using Linq?
Searched long on this site and in Google but found nothing for this particular request ... Thanks for your help

Use this:
var ids = new int[]{1,2};
var docs = context.Documents
.Where(d=> ids.All(cid=> d.Categories.Any(dc=>dc.cat_id == cid))).ToList();
Or
var ids = new int[]{1,2};
var result = from d in context.Documents
where ids.All(id => d.Categories.Any(dc=> dc.cat_id == id))
select s;

Related

three level hibernate query join one to many relationship

I have 3 tables
table 1
country
countryid countryname
this table has a one to many join to table 2 that is state
table 2
state
stateid statename countryid
table 2 has a one to many join to city table
table 3
city
cityid cityname stateid
i tried to read country using query
session.createQuery("from Country c where c.countryName=:countryname order by c.countryName");
it gives me country object but the list of states are empty??
what am i doing wrong???
ok i fixed it.
by using cascade.all in #oneToMany annotation
and changed the hql to criteria query.
Criteria criteria = session.createCriteria(Country.class, "country");
criteria.add(Restrictions.eq("country.countryName", countryname));

LINQ TO Entitites : Combining Two Non Related Tables in Query

I have two tables:
Relationships (ID, UserID, Type, Contact ID)
Contacts (ID, Name, Address)
When the type is 5 in Relationship table, Contact ID is the ID in the Contacts table.
I want to get all the contacts information for a particular user
Here is what I have :
IEnumerable<Relationship> rels = user.Relationships.Where(r => r.Type==5)
foreach (Relationship r in rels)
{
contact = contactRepository.Find(r.ContactID); // Returns Contact Object
Relation relation = new Relation(r, contact);
RelationList.Add(relation);
}
Is this correct way to do this?
I have seen other post mentioning TPC. However, I did not quite understand all that and it seemed TPC only works for code first process.
You can user followng linq statement to get the contacts of a given userID (let's say UserID=15) by using relatonships and contacts tables:
var contacts=from r in Relationships
join c in Contacts on r.ContactID equals c.ID
where r.Type=5 and r.UserID=15
select c;

LINQ Query for fetching data from Multiple Tables

I am working in Asp.Net 4.0 C#-- MVC-3. I have one problem and don't know how to solve. I have 4 tables and want to fetch data from that tables with LINQ.
TABLES
1) Project_Master
Field Names :
project_id (pk)
project_name
company_id (FK with company_master)
company_category_id (FK with Company_Category_master)
project_status_id (FK with Project_Status_Master)
2)Company_Master
Field Names :
company_id
company_name
company_category_id (FK with Company_Category_Master)
3) Company_Category_Master
Field Names :
Company_Category_Id
Company_Category_Name
4) Project_Status_Master
Field Name :
Project_Status_Id
Project_Status_Name
Below are the fields I need to fetch..(using LINQ Query)
Company_Name
Total completed project using status id(1)=complete (where staus 1 means completed)
Total Project
Company_category_name
So, how can I fetch data with linq query??
Thanks in advance...
Try the below example:
(From lse In Me.Leases, nty In Me.Entities, psg In Me.ProductionStages, lsg In LeaseStages _
Where lse.LeaseName = leaseName _
Select lse, lsg, nty, psg).Single
or you can use below example too:
var employeesQuery = from populationTable in db.Populations
join personTable in db.Persons on populationTable.Guid equals personTable.PopulationGuid
join employeeTable in db.Employees on personTable.Guid equals employeeTable.PersonGuid
select new { populationTable, personTable, employeeTable};

Linq query that results in one field in parent entity being a collection of child entities

I am trying to write a Linq query that results in a parent entity with one of the fields being a collection of entities of its related children. For example, I have a collection of all customers entities and a collection of all orders entities. The orders entities have a field called customerPK which contains the link to the related parent customer entity. I want to create a Linq query that joins the two collections and results in all the fields of the customer entity plus an additional field which is the collection object of all the related order entities for that specific customer entity.
Hopefully this should do the trick;
EDIT: Code updated to perform a Left Outer Join, based on this example; http://smehrozalam.wordpress.com/2009/06/10/c-left-outer-joins-with-linq/. This now includes Customers who have no orders.
var query = from c in customers
join o in orders on c.ID equals o.CustomerPK into joined
from j in joined.DefaultIfEmpty()
group j by c into g
select new { Customer = g.Key, Orders = g.Where(x => x != null) };
Note, the use of Where on the selection of the Orders grouping is so that null orders are filtered out at this point, instead of ending up with a grouping containing a single null Order for customers who don't have orders.
Then some example usage;
foreach (var result in query)
{
Console.WriteLine("{0} (ID={1})", result.Customer.Name, result.Customer.ID);
foreach (var order in result.Orders)
{
Console.WriteLine(order.Description);
}
}
This example results in an object with two fields, the Customer and then a group of related Orders, but there's no reason why you can't select the individual fields of your customer object in the query as you specified in your post.

LINQ Joining 2 tables

I have two tables in the database one contains a list of all possible grocery values. For Example
Milk
Cheese
Bread
Meat
the second table contains Items from Grocery that are selected. For Example:
Milk
Cheese
I want a result that has all possible grocery items with Milk and Cheese selected.
Any ideas?
Here are the tables.
The GroceryList Table:
ID INT PK
Description Varchar(50)
The ShoppingList Table:
ID INT PK
GroceryListID int FK to GroceryList.ID
So the resulting Entity would be all items from GroceryList and if they exist in ShoppingList then selected is marked as true:
ShoppingList.ID
Grocerylists.Description
Selected
Based on understanding you can do something like this
//first get the list of product which satisfy your condition
var ids = (from p ShoppingList
select p.GroceryListID ).ToList();
//second filter the Grocery products by using contains
var myProducts = from p in GroceryList
where ids.Contains(p.ID)
Select p;
or
if you want to get info about join than this image would help you
Inner Join
Outer Join
Try to understand and which may help you to resolve your query
Edit: Still sounds like you want to do a left join. In your case:
var LINQResult = from g in Datacontext.GroceryList
from s in DataContext.ShoppingList
.Where(c=>c.ID == g.ID)
.DefaultIfEmpty()
select new {
g.ID,
g.Description,
s.ID // Will be null if not selected.
};
For more examples:
Left Join on multiple tables in Linq to SQL

Resources