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};
Related
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));
I have table with and ProjectId and more data for instance Name and Quantity.
I have another table with ProjectId, ProjectType and NumberOfthings
How can I created a calculated column that has the summatory of the NumberOfThings values by Project Type and ProjectId ?
For instance getting data by projecttype F in this example I should get in the calculated columns the follow values.
You can use a query to summarize the number of things by ProjectID and ProjectType
SELECT Table1.ProjectID AS ID, Table2.ProjectType AS Type, Sum(Table2.NumberOfThings) AS Things
FROM Table1 INNER JOIN Table2 ON Table1.ProjectID = Table2.ProjectID
GROUP BY Table1.ProjectID, Table2.ProjectType;
Results:
ID Type Things
1 F 3
2 G 34
3 F 100
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.
I'm trying to write a Oracle SQL query and I'm unable to get the right result.
For the tables below, I would like to first get all records from DEVICE where DEVICE.MODEL='UNITA' and for those results, give me the DEVICE.CUSTOMER_ID's who don't have a record where PROFILE.TYPE='TEST' joining both tables on CUSTOMER_ID. Any ideas on how to formulate this query?
TABLE DEVICE:
ID - sequence generated primary key (NUMBER (10))
DEVICE_NUMBER - unique (varchar)
CUSTOMER_ID (varchar)
MODEL (varchar)
TABLE PROFILE:
ID - sequence generated primary key (NUMBER (10))
CUSTOMER_ID (varchar)
TYPE (varchar)
If I understand the requirement, this should do the trick:
SELECT d.ID, d.Device_Number, d.Customer_ID, d.Model
FROM Device d
LEFT JOIN Profile p ON d.Customer_ID = p.Customer_ID
WHERE d.Model = 'UNITA'
AND (p.ID IS NULL OR p.Type = 'TEST')
It works because of the LEFT JOIN, which will make Profile.ID NULL if there's not a matching Profile row for the Customer_ID. If there is a matching row, the test for Profile.Type = 'TEST' will determine what's included.
There's a SQL Fiddle here. The Fiddle includes the Profile.ID and Profile.Type values in the results because I think they help explain things more clearly.
Addendum: Some confusion on my part over the requirements; this query may be closer to what's needed:
SELECT d.ID, d.Device_Number, d.Customer_ID, d.Model, p.id AS pid, p.type
FROM Device d
LEFT JOIN Profile p ON d.Customer_ID = p.Customer_ID AND p.Type = 'TEST'
WHERE d.Model = 'UNITA'
AND p.ID IS NULL
I need to move some code from C# into a Stored Procedure for speed reasons. What I'm trying to get is a unique list of TemplateIds from the RoleTemplates (or CategoryToRoleTemplate) table based on a CategoryId.
However, I need the query to walk the Category.ParentId relationship, and collection all of the parent's related TemplateIds. This needs to happen until the ParentId is null.
Ideally the result should be a unique list of RoleTemplate.TemplateIds.
Table structure...
Categories
------------------------------
CategoryId uniqueidentifier
ParentId uniqueidentifier <-- Relationship to Categories.CategoryId.
Name varchar (50)
CategoryToRoleTemplate
------------------------------
CategoryId uniqueidentifier <-- Relationship to Categories.CategoryId.
TemplateId uniqueidentifier <-- Relationship to RoleTemplates.TemplateId.
RoleTemplates
------------------------------
TemplateId uniqueidentifier
Name varchar (50)
I'm using SQL Server 2008 R2.
Thanks!
EDIT:
Final solution:
with CategoryHierarchy (ParentId)
as (
-- Anchor member definition
select CategoryId from Categories
where CategoryId = #id
union all
-- Recursive member definition
(select c.ParentId from Categories as c
inner join CategoryHierarchy as p
on c.CategoryId = p.ParentId)
)
select distinct TemplateId from CategoryToRoleTemplates where CategoryId in (select CategoryId from CategoryHierarchy);
Thanks to all who answered! CTEs were the key.
I would suggest a CTE for doing that query. Keep in mind though that the tree will actually START at null and go until exhausted.
Example (may or may not work OOB given your code):
; WITH CategoryTree(CategoryID, sorthelp) AS
(SELECT CategoryID, 0 FROM Categories WHERE ParentID IS NULL)
UNION ALL
(SELECT C.CategoryID, CT.sorthelp + 1 FROM Categories C INNER JOIN CategoryTree CT ON C.PARENTID = CT.CategoryID)
SELECT DISTINCT TemplateID FROM RoleTemplates WHERE CategoryID IN (SELECT CategoryID FROM CategoryTree)
Good Point(tm): Don't forget the semicolon before the WITH keyword.
Use a recursive common table expression:
http://msdn.microsoft.com/en-us/library/ms186243.aspx
Please check this link http://msdn.microsoft.com/en-us/library/ms186243.aspx
I would go first with the table Categories with the with syntax and after that join with the others tables.
I'm short on time at the moment, so I can't be specific, but I would look into Common Table Expressions, which I've used successfully in the past to implement recursion.