If I have a model that has several tables, and I am joining these tables together into a flat table within my controller class, how do I get the view to be able to access the flat table?
For example, let's say I have three tables in my model (customers, orders, invoices).
Orders are linked to customer by a foreign key (CustomerID), and invoices are linked to orders by a foreign key (OrderID).
In order to see all of this in one flat table (with all customers listed, even if they don't have orders, and all orders listed, even if they don't have invoices), I have the following anonymous type:
var FlatTable = (from a in customers
let CustomerID = a.ID
join b in orders on a.ID equals b.CustomerID into ab
from b in ab.DefaultIfEmpty()
let OrderID = b.ID
join c in invoices on b.ID equals c.InvoiceID into ac
from c in ac.DefaultIfEmpty()
let InvoiceID = c.ID
select new {a.CustomerName, CustomerID, OrderID, b.ProductDescription, InvoiceID, c.InvoiceAmount});
return View(FlatTable.ToList());
Then in my View (which is based on my model), how am I able to access FlatTable.
IList<ViewModel> model = (from a in customers
join b in orders on a.ID equals b.CustomerID into ab
from b in ab.DefaultIfEmpty()
join c in invoices on b.ID equals c.InvoiceID into ac
from c in ac.DefaultIfEmpty()
select new ViewModel() {CustomerName = a.CustomerName, CustomerID = a.ID, OrderID = b.ID, ProductDescription = b.ProductDescription, InvoiceID = c.ID, InvoiceMaount = c.InvoiceAmount}).ToList();
Related
I have three tables that I would like to select from
Table 1 has a bunch of static information about a user like their idnumber, name, registration date
Table 2 has the idnumber of the user, course number, and the date they registered for the course
Table 3 has the course number, and the title of the course
I am trying to use one query that will select the columns mentioned in table 1, with the most recent course they registered (name and date registered) as well as their first course registered (name and date registered)
Here is what I came up with
SELECT u.idst, u.userid, u.firstname, u.lastname, u.email, u.register_date,
MIN(l.date_inscr) as mindate, MAX(l.date_inscr) as maxdate, lc.coursename
FROM table1 u,table3 lc
LEFT JOIN table2 l
ON l.idCourse = lc.idCourse
WHERE u.idst = 12787
AND u.idst = l.idUser
And this gives me everything i need, and the dates are correct but I have no idea how to display BOTH of the names of courses. The most recent and the first.
And help would be great.
Thanks!!!
You can get your desired results by generating the min/max date_inscr for each user in a derived table and then joining that twice to table2 and table3, once to get each course name:
SELECT u.idst, u.userid, u.firstname, u.lastname, u.email, u.register_date,
l.mindate, lc1.coursename as first_course,
l.maxdate, lc2.coursename as latest_course
FROM table1 u
LEFT JOIN (SELECT idUser, MIN(date_inscr) AS mindate, MAX(date_inscr) AS maxdate
FROM table2
WHERE idUser = 12787
) l ON l.idUser = u.idst
LEFT JOIN table2 l1 ON l1.idUser = l.idUser AND l1.date_inscr = l.mindate
LEFT JOIN table3 lc1 ON lc1.idCourse = l1.idCourse
LEFT JOIN table2 l2 ON l2.idUser = l.idUser AND l2.date_inscr = l.maxdate
LEFT JOIN table3 lc2 ON lc2.idCourse = l2.idCourse
As #BillKarwin pointed out, this is more easily done using two separate queries.
Here are the tables
Customer (Id, Name, Address, City, State, Zip)
Account (Id, CustomerID, OpenDate, CloseDate, Type, Balance)
Transaction (Id, AccountId, Amount, BranchId...)
Branch (Id, Name, Address, City, State, Zip)
And the question goes: List the names of the customers who made transactions of an amount exceeding $100 any bank branch in Seattle.
I am thinking about something like this, but I am not sure how to do the rest from here:
SELECT Name
FROM Customer c
JOIN Account a ON a.CustomerID = c.Id
JOIN
Please help, Thank you!!
SELECT c.Name FROM Customer c INNER JOIN Account a ON c.Id = a.CustomerID INNER JOIN TRANSACTION t on t.AccountId = a.Id INNER JOIN BRANCH b ON t.BranchID = b.Id WHERE t.AMOUNT > 100 AND t.branch = "Seattle"
I have some interesting code to look at.
I have three tables:
Table A has 4 columns:
TablePK
UserID
TableBFKID
Score
Table B has 3 columns:
TablePK
Name
ShortName
Table c has 4 columns:
TablePK
ScoreMin
ScoreMax
Modifier
So when the full join happens it looks like this:
SELECT B.ShortName
, A.Score
, C.Modifier
FROM TableA A
INNER JOIN TableB B ON a.TablePK= B.TablePK
INNER JOIN TableC C ON A.Score BETWEEN C.ScoreMin AND C.ScoreMax
The results would look like this:
ShortName, Score, Modifier. EX:
CHA, 19, 4
Now I know how to do an Entity Framework join if there is an actual PK or FK, or even if there is only a 0:1 relationship.
But how do you do the join when there is neither a PK nor an FK?
LINQ, including LINQ to Entities, only supports equi-joins.
But you can run SQL directly:
var res = myContext.Database.SqlQuery<TResult>("SQL goes here", parmeters...);
and EF will map the columns of the result set to the properties of TResult (which needs to other connection to the context: it does not need to be an entity type with a DbSet typed property in the context).
In this case I wouldn't try to join them, just use a sub-select in your linq to select from the un-joined table where the scores are between your wanted ranges.
var results = context.TableA
.Select(a => new {
score = a.Score, //add all needed columns
tableCs = context.TableC.Where(c => a.Score >= c.ScoreMin && a.Score <= c.ScoreMax)
});
I'm using linq to sql on my asp.net project and i locked in somewhere. I select data amoung relationship tables and I use following codes. But the question is if supplierID is different than 0 there is no problem for query. Query is working as successful. But if supplierId is 0 query returns nothing. I want to use if statement when i join tables but how ?
My Codes,
EnvanterDataContext dc = new EnvanterDataContext();
var invent = from equipment in dc.tEquipments
where equipment.EquipmentID == id
orderby equipment.EquipmentID descending
join supplier in dc.tSuppliers on equipment.SupplierID equals supplier.SupplierID
join model in dc.tModels on equipment.ModelID equals model.ModelID
join equipmentType in dc.tEquipmentTypes on equipment.TypeID equals equipmentType.EquipmentTypeID
join equipmentStatus in dc.tEquipmentStatus on equipment.StatusID equals equipmentStatus.EquipmentStatusID
select equipment;
I want to use
EnvanterDataContext dc = new EnvanterDataContext();
var invent = from equipment in dc.tEquipments
where equipment.EquipmentID == id
orderby equipment.EquipmentID descending
if(equipment.SupplierID != 0)
join supplier in dc.tSuppliers on equipment.SupplierID equals supplier.SupplierID
join model in dc.tModels on equipment.ModelID equals model.ModelID
join equipmentType in dc.tEquipmentTypes on equipment.TypeID equals equipmentType.EquipmentTypeID
join equipmentStatus in dc.tEquipmentStatus on equipment.StatusID equals equipmentStatus.EquipmentStatusID
select equipment;
Thanks inadvance.
I am having three tables viz. Bids(bid_id,base_price),Customer(customer_id,name,..) and Customer_Bid(customer_id,bid_id,bidding_amount) where customer bids and his bidded amount is stored in Customer_Bid table.
I want to show the details of customer along with his bidded id and the one with highest bid for same bid id.
I have tried to get the customer details but i am not able to show his bidded amount along with the highest bidded amount whish resides in same table.
Plz any one can help me out.
Thanks.
Edit This is the query that was in the comment
select cb.bid_id, c.customer_id ,MyBid=cb.total_bidding_ammount
, HighestBid= max(cb.total_bidding_ammount)
from customer as c
,customer_bidding as cb
,bid as b
group by cb.bid_id, c.customer_id, cb.total_bidding_ammount
If you change this:
, HighestBid= max(cb.total_bidding_ammount)
to something like this:
, HighestBid =
(select max(bidding_ammount)
from customer_bidding
where bid_id = bid.bid_id)
You will on the right track.
Try this one:
SELECT cb.bid_id,
c.customer_id,
cb.total_bidding_ammount,
topbids.customer_id as topbid_customer_id,
topbid
FROM customer c
INNER JOIN customer_bidding as cb
ON c.customer_id = cb.customer_id
INNER JOIN (
SELECT cb.bid_id, c.customer_id, MAX(cb.total_bidding_ammount) as topbid
FROM customer c
INNER JOIN customer_bidding cb
ON (c.customer_id = cb.customer_id)
GROUP BY cb.bid_id
) topbids
ON cb.bid_id = topbids.bid_id
select a.*, b.bidding_amount,
e.bidding_amount as highest_bid
from customer a
inner join customer_bid b on a.customer_id = b.customer_id
inner join bids c on b.bid_id = c.bid_id
join
(select * from (
select bidding_amount,bid_id
from customer_bid
order by bidding_amount desc
) d group by d.bid_id) e on b.bid_id = e.bid_id