How can I linq 3 tables - linq

How can I linq 3 tables where I can link a student to a school. Tables are: Students, Depart, School.
studentId(pk), departId(fk) departId(pk), schoolId(fk) schoolId(pk)
Below is linking two tables
#foreach (var student in Model.students.Where(s => s.schoolId == item.schoolId))

what you want exactly ? you can join them ...
var query = (from depart in Model.Depart
join school in Model.School on depart.departId equals school.departId
join student in Model.students on school.schoolId equals student.schoolId
where students.schoolId == item.schoolId
select new
{
depart,
school,
student
});
or...

If you have your associations cdonfigured properly, instead of joins, you could also use the associations:
var query = from school in Model.Schools
from dept in school.Departments
from student in dept.Students
select new { student, dept, school};

Related

LINQ Equivalent of and SQL query with two inner joins and a left join

I would be grateful for help with a LINQ equivalent of the following SQL Query (which works). Below this SQL query I give some description of my simple data base and the problem I want to solve.
Select a.Name, a.OrderID,
b.ProductIDFirst, c1.productName ProductNameFirst,
b.ProductIDSecond , c2.productName ProductNameSecond
from Customers a
INNER JOIN ORDERS b ON a.OrderID = b.OrderID
left join products c1 on b.productidfirst = c1.productid
left join products c2 on b.ProductIDSecond = c2.productid
Background information on the database structure:
I have a simple SQL Server Database with three Tables named Products, Orders and Customers.
The business model is such that each order can have only two products (not more).
The Orders table has two foreign keys, though they both come from the Products table. These Foreign Key field Names in the Orders Table are ProductIDFirst and ProductIDSecond. These two Foreign Keys in the orders table correspond to two products that each order can have. Customers table has one Foreign Key which comes from the Orders Table.
Now I need help with an LINQ query that will return me all customers such that I get five fields - CustomerName, OrderID and Names of each of the two products that match the OrderID in the customer product.
Your links are non-existent, so here's a best attempt without seeing anything.
Assuming you have the following containers (you'll need to change them for your scenario):
var customers = new List<Customer>();
var orders = new List<Order>();
var products = new List<Product>();
You can do the following:
var query =
from a in customers
join b in orders
on a.OrderId equals b.OrderId
join c1 in products
on b.ProductIdFirst equals c1.ProductId into c1a
join c2 in products
on b.ProductIdSecond equals c2.ProductId into c2a
from p1 in c1a.DefaultIfEmpty()
from p2 in c2a.DefaultIfEmpty()
select new
{
Name = a.Name,
OrderId = a.OrderId,
ProductIdFirst = p1 == null ? null : p1.ProductIdFirst,
ProductNameFirst = p1 == null ? null : p1.ProductNameFirst,
ProductIdSecond = p2 == null ? null : p1.ProductIdSecond,
ProductNameSecond = p2 == null ? null : p1.ProductNameSecond,
};
In short, where you want a left join, project the join into something else (e.g. c1a, c2a) then call from on them using DefaultIfEmpty() which will set null when no matching item exists on the right-hand-side.

How to return values from query when joining multiple tables in Linq?

I have a Linq queries that have tables join and couple of tables inner join together. Sometimes I got an error from the query when table is empty. What I trying to do is I am tryting to get a value from table even if other table is empty.
Thanks in Advance.
You need to do left join
Assuming left join between customer and order table.
var query =
from customer in dc.Customers
from order
in dc.Orders
.Where(o => customer.CustomerId == o.CustomerId)
.DefaultIfEmpty()
select new { Customer = customer, Order = order }
Also refer below link
http://forums.asp.net/t/1792428.aspx/1

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;

translate raw MySQL into Doctrine 1.2

I'm having a heck of a time translating the following raw MySQL query, which has been tested and works very well, into doctrine 1.2:
SELECT
r.name AS regionname,
s.name AS statename
FROM
job j
LEFT JOIN
community c ON c.id = j.community_id
LEFT JOIN
state s ON s.id = c.state_id
LEFT JOIN
region r ON r.id = s.region_id
WHERE
r.id = 1
This does not work:
$q = Doctrine_Query::create()
->select('r.name AS regionname', 's.name AS statename')
->from('job j')
->leftJoin('community c ON c.id = j.community_id')
->leftJoin('state s ON s.id = c.state_id')
->leftJoin('region r ON r.id = s.region_id')
->where('r.id = 1')
->execute();
Here's my db structure, if it is useful:
job:
columns:
id
community_id
relations:
community: local_key: community_id, foreign_key: id, foreignAlias: Communitys
community:
columns:
id
state_id
relations:
state: local_key: state_id, foreign_key: id, foreignAlias: States
state:
columns:
id
name
region_id
relations:
region: local_key: region_id, foreign_key: id, foreignAlias: Regions
region:
columns:
id
name
I have noticed the same thing as well. Doing joins in Doctrine 1.2 is a little bit different from mysql. To do a join, you have to take advantage of the relationships that Doctrine creates in each component in your case the job class.
You can check the job's base class for these relationships I am talking about. In the setup method, they look like this for example for a community foreign key id in the job table:
$this->hasOne('community as Communitys', array(
'local' => 'community_id',
'foreign' => 'id'));
Back to your question, to do a join you have to reference the alias of the table where the foreign key belongs to. For example if you want to join on the community table with the alias Community:
->leftJoin('j.Community')
instead of
community c ON c.id = j.community_id
Notice that I didn't say join on id because in Doctrine 1.2 that is implied already. You can however choose to join on something else.
Likewise if tables you have previously joined to need to be joined to other tables they have foreign keys to you have to
1.use their alias in the current queryand
2.reference the component as stated in THEIR base class as well.
So you said that you want to join community to states in the current query the way you should do it is
// join job and community first
->from('job j')
->leftJoin('j.Community c')
// join community to state since they are the ones that are related
->leftjoin('c.States s')
From here I hope you can see the pattern. At the end of the day if you look at it the idea of joining is still the same with raw sql, the only difference is the syntax:
SQL syntax:
LEFT JOIN
community c ON c.id = j.community_id
DQL syntax:
->leftJoin('j.Community c')
Anyway to answer your question, here is how the join should somewhat be done:
$q = Doctrine_Query::create()
->select('*')
->from('job j')
->leftJoin('j.Community c')
->leftJoin('c.State s')
->leftJoin('s.Region r')
->where('r.id = 1')
->execute();

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