I am having trouble getting one of my LINQ to SQL queries to work correctly. I have three tables setup as follows:
Vendors
id - primary key
Manufacturers
id - primary key
ManufacturerVendorRelationships
id - primary key
manufacturer_id - foreign key to manufacturer.id
vendor_id - foreign key to vendor.id
I am trying to write a LINQ to SQL query that will fetch the Vendors that are not currently related to a given manufacturer. For example, the following table data should only result in 2 vendors for the manufacturer with ID of 1. Can someone please help me with the LINQ to SQL for this example? Right now, the application is doing this logic. Thanks in advance.
Vendors
ID
1
2
3
4
5
Manufacturers
ID
1
2
3
4
5
ManufacturerVendorRelationships
ID ManufacturerID VendorID
1 1 1
2 1 2
3 1 3
Maybe something like this:
var result=(
from v in db.Vendors
where !db.ManufacturerVendorRelationships
.Select(s=>s.VendorID)
.Contains(v.ID)
select v
);
Or if you want it like a field:
var result=(
from v in db.Vendors
select new
{
v.ID,
HasManufacturer=db.ManufacturerVendorRelationships
.Select(s=>s.VendorID)
.Contains(v.ID)
}
);
where db is the linq data context
int id= 1;
var result =
dc.Vendors
.Where(v => !dc.ManufacturerVendorRelationships
.Any(rel => rel.VendorId == v.Id && rel.ManufacturerId == id));
Related
I'm stuck with this linq query.
I've this tables.
ID A B C D
1 some data
2 some other data
Then, For every record on that table I may have none or many rows
ID TableA_ID R
1 1 1
2 1 2
3 1 5
4 2 2
For example. Row 1 (some data) has 3 rows on table B.
I tried using
tableA.Include(x => x.tablebchilds.Where( d => d.R == 1)).ToList()
but it is not working. With many others varation.
The objective of this query is to return tableA.row #1 if I pass it 1 as value (value of R). Number <> 2 won't give any result.
Tables are linked on EF. So TableB.tableA_ID is Foreign key of tableA.ID
Edit #1
I tried the answers in the question marked as duplicated with no luck. Give that 2 tableA.rows if the user insert 1 as parameter, linq query should return Row #1, some data. If 2 is passed as parameter, nothing is return.
A working SQL statement is:
SELECT [TableA].* FROM [TableA] JOIN [TableB] ON [TableA].[Id] = [TableB].[TableA_Id] WHERE [TableB].[R] = 1
Thanks!
If you have database relationship properly configured this have to work.
tableA.Include(x => x.tableBChilds).Where(tableA => tableA.tableBChilds.Any(b => b.R== 1)).ToList();
I am not sure how possible this is but I have two tables and I want to grab a value from table 2 via the value of table 1.
Table 1 has the a Foreign Key called "rank" which is an int. Table 2 has a value called "name" which is a string. Now Table 1's "rank" correlates to Table 2's "ID".
So when I say
var result =
db.Table1.Select(x => new { x.name, x.rank }).ToList();
//Bob - 2
I really want to say something like
var result =
db.Table1.Select(x => new { x.name, Table2.rank.Where(ID == x.rank) }).ToList();
//Bob - Gold
I am still new to LINQ though and I am not sure how to get rank's string value from the other table within a query like this.
EDIT
Tables I am using and their relational values.
User: ID (PK), s1elo (FK to PastElos), champ (FK to ChampionList), elo (FK to EloList)
PastElo: ID (PK), Rank
ChampionList: ID (PK), name
EloList: ID (PK), Rank
Working example for Users and PastElo
var result =
db.Users.Join(db.PastEloes,
x => x.s1elo, y => y.ID, (x, y)
=> new { y.Rank, x.name, x.other_items_in_Users }).ToList();
Note: PastElo is PastEloe's due to EF making everything plural when I synced up my DB, thus why User is also Users, I think that is referred to as the "context".
You could try something like the following:
var result = db.Table1.Join(db.Table2,
x=>x.rank,
y=>y.ID,
(x,y) => new { x.rank, y.Name }).ToList();
In the above linq query we make a Join between the two tables, Table1 and Table2 based on the association and then we select that we want.
Another way you could try to write this query would be the following:
var result = (from t1 in db.Table1
join t2 in db.Table2
on t1.rank equals t2.ID
select new { t1.rank, t2.Name, }).ToList();
Another way to do this would be to include your Database relationships in your C# entities. You could use EntityRef here. See the following documentation:
https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/sql/linq/how-to-map-database-relationships
i have got this table that relates the Table hardware with a table Process..
this table is called processHardware.
this table is discribed by:
IDProcessHardware
IDProcess
IDHardware
State
the field state can have 3 states (1-Insert, 2-Remove,3-Substitute)..
so i can i have this:
IDProcessoHardware IDProcesso IDHardware State
1 10 1 1
2 10 2 1
3 10 1 2
what this tell me is that the hardware with id 1 was insert on the process with the id 10
then the user insert the hardware with id 2 on the process with the id 10, and the it remove the hardware with the id 1 from the process with the id 10
by giving the id of the process i want to get the id of the hardware that were insert, this is, the id of the hardware that were remove..
so in this case the record that i will get is record number 2..because was insert, but was not removed..
after getting the ids from this table i need to relate the ids with the table hardware, this table is described by idhardware, serial number, description..
i was using linq method base..
and this was something that i did, but didnt go further after this..
var ProcessoHardware = from procHardware in db.ProcessoHardwares
where procHardware.Rem == 0 && procHardware.IDProcesso == IDProcesso
group procHardware by procHardware.IDHardware into g
select new { IDHardware = g.Key, count = g.Count() };
the query above didnt work for me...
so i want to get the records that appears only once on the table, and then relate the ids that were obtained from this query and get the info about those ids like, serial number, description(these fields are on a table called Hardware).
thanks in advance..
in sql i manage to do the query ..
SELECT *
FROM
(SELECT IDHardware ,COUNT(IDHardware) nu
FROM dbo.ProcessoHardware
WHERE IDProcesso=47
Group By IDHardware) T WHERE nu=1
how do i pass this to linq?
Firstly your SQL statement would be clearer if you used the having clause so it becomes
SELECT IDHardware, COUNT(IDHardware) nu
FROM dbo.ProcessoHardware
WHERE IDProcesso=47
GROUP BY IDHardware
HAVING COUNT(IDHardware) = 1
secondly, your SQL statement doesn't mention a field called Rem, but your LINQ states where procHardware.Rem == 0. I'm going to assume that you need to keep that filter. If so then all you need to do is add a where clause to count your group, g. Try the following
var ProcessoHardware = from procHardware in db.ProcessoHardwares
where procHardware.Rem == 0 && procHardware.IDProcesso == IDProcesso
group procHardware by procHardware.IDHardware into g
where g.Count() == 1
select new { IDHardware = g.Key, count = g.Count() };
although the literal transformation of your statement (without the Rem and hard coded ID of 47) to LINQ would be
var ProcessoHardware = from procHardware in db.ProcessoHardwares
where procHardware.IDProcesso == 47
group procHardware by procHardware.IDHardware into g
where g.Count() == 1
select new { IDHardware = g.Key, count = g.Count() };
Say we got a Database design like this.
Customer
Id Name
1 John
2 Jack
Order
Id CustomerId
1 1
2 1
3 2
OrderLine
Id OrderId ProductId Quantity
1 1 1 10
2 1 2 20
3 2 1 30
4 3 1 10
How would I create an entity framework query to calculate the total Quantity a given Customer has ordered of a given Product?
Input => CustomerId = 1 & ProductId = 1
Output => 40
This is what I got so far, through its not complete and still missing the Sum.
var db = new ShopTestEntities();
var orders = db.Orders;
var details = db.OrderDetails;
var query = orders.GroupJoin(details,
order => order.CustomerId,
detail => detail.ProductId,
(order, orderGroup) => new
{
CustomerID = order.CustomerId,
OrderCount = orderGroup.Count()
});
I find it's easier to use the special Linq syntax as opposed to the extension method style when I'm doing joins and groupings, so I hope you don't mind if I write it in that style.
This is the first approach that comes to mind for me:
int customerId = 1;
int productId = 1;
var query = from orderLine in db.OrderLines
join order in db.Orders on orderLine.OrderId equals order.Id
where order.CustomerId == customerId && orderLine.ProductId == productId
group orderLine by new { order.CustomerId, orderLine.ProductId } into grouped
select grouped.Sum(g => g.Quantity);
// The result will be null if there are no entries for the given product/customer.
int? quantitySum = query.SingleOrDefault();
I can't check what kind of SQL this will generate at the moment, but I think it should be something pretty reasonable. I did check that it gave the right result when using Linq To Objects.
I have three tables and I have used edmx designer to add associations between them. Below is how they are linked.
(table1) Loans - (table 2) Investor : Many to One relationship
(Table2) Investor - (Table3) InvestorInfo : One to Many relationship
I want to get [1] Total loans count sold to one investor, [2] Investor name and [3] investor's service fee which is stored in Table3 at idx = 2005 for each investor ("investor id & idx" is primary key of table3 - InvestorInfo table).
How do I do that in below query? I am forced to select 'FirstOrDefault()' to access any column in Table3 (See commented lines). If I use FirstOrDefualt, I get a record where idx = 1 and not 2005.
var loanPurchaseData = (from cd in entity.Table1
//where cd.Table2.Table3.Select(x => x.IDX == 2005)
//where cd.ULDD_SET_POOLS.ULDD_SET_POOLDT.FirstOrDefault().SORT_ID == 2005
group cd by new { cd.Table4.PurchaseDate, cd.Number } into grp
select new
{
investor = grp.FirstOrDefault().Investor,
no_of_loans = grp.Count(),
sort_id = grp.FirstOrDefault().Table2.Table3.FirstOrDefault().SORT_ID,
service_fee_rate = grp.FirstOrDefault().Table2.Table3.FirstOrDefault().DT_REAL_PERC_VALUE
}).ToList();
Your question is not very clear - I don't understand whether idx is in Table3 or Table1, and what you want to select, but I will assume you have a many-one-many schema, where an Investor has zero or more Loans & zero or more InvestorInfos. You want to get, say, all of the loans which join to investor info with idx = 2005. Correct me if I'm wrong, and correct your question if I'm right!
Starting with your InvestorInfo object, you know that there's only one Investor but there will be zero or more Loans.
// only one InvestorInfo for idx, but this isn't clear in your question
var investorInfo = context.InvestorInfos.SingleOrDefault(i => i.idx == 2005);
var loans = investorInfo.Investor.Loans;
The crux of your problem is that you cannot get 'the loan service fee' for an investor info. Why not? Because that investor has 5 loans. Which one do you want?
-- we can get the maximum, minimum, sum, etc...
var max = loans.Max(l => l.DT_REAL_PERC_VALUE);
var min = loans.Min(l => l.DT_REAL_PERC_VALUE);
var min = loans.Sum(l => l.DT_REAL_PERC_VALUE);
Again it's not clear what you are trying to do, nor what your data actually looks like, but in a one-many relationship you will necessarily have more than one of the 'many' side for each of the 'one' side.
To get the max, use the Max operator.
service_fee = grp.Max(l => l.Table2.Table3.Max(t => t.DT_REAL_PERC_VALUE))