Linq To Sql Sub Query Complex - c#

tblItem
Name
ProductID
tblProduct
Name
ProductID
CategoryID
tblCategory
Name
CategoryID
var itms = from item in CMP.tblItems
let t2s = (from g in CMP.tblProducts
where g.CategoryID==CatID
select g.ProductID)
where item.Name.Contains(Model) && item.ProductID.ToString() == t2s.ToString()
select new { item.Name };
My problem is more than one product is return to t2s (Sub-Query). if i add FirstOrDefault() to Sub-Query then it will match it with only one product id! i need to match will all productid(s) it returns.

Try This One:
var itms=from item in CMP.tblItems
from g in CMP.tblProducts
where item.Name.Contains(Model) && item.ProductID == g.ProductID && g.CategoryID == CatID
select new {item.Name};

Use the navigation properties that LINQ-to-SQL creates for you. Item should have property Product. So you can simply do this:
var itms = from item in CMP.tblItems
where item.Name.Contains(Model) && item.Product.CategoryID = CatId
select new { item.Name };

Related

how to apply join or innerquery to connect two table

Here MyChildTable contains only id and the parent table contains id + name.
I have written a query to fetch the existing data from the table
await _dbContext.MyChildTable
.Where(c => c.CustomerId == **(select customerid from tableParent where customername= reqcustomername)**
Here i want to match customerId with the matching customer id from the second table ie tableParent.How to replace the query in to linq to get the proper record.select customerid from tableParent where customername= reqcustomername i want to replace this selection
I don't understand what you mean
so my maybe answer error
LINQ
using (entity entityData = new entity())
{
var checkqry2 = from T1 in entityData.MyChildTable.AsNoTracking()
join T2 in entityData.tableParent on
T1.CustomerId equals T2.customerid
where T1.customerid == "ID" && T2.customername == reqcustomername
group new { T2.customerid, T2.customername } by new { T1.customerid, T1.customername } into c
orderby c.Key.customerid
select new { customername=c.Key.customername,
customerid=c.Key.customerid,
};
}
you can try entity lambda
entity lambda
using (entity entityData = new entity())
{
var query1 = entityData.MyChildTable
.Join(entityData.tableParent , o => o.CustomerId , p => p.CustomerId , (o, p) => new
{
o.CustomerId,
p.customername,
}).Where(o => o.CustomerId == "123" && o.customername == "name").ToList();
}
Here I want to match customerId with the matching customer id from the
second table ie tableParent.How to replace the query in to linq to get
the proper record.select customerid from tableParent where
customername= reqcustomername i want to replace this selection
Well, lot of way around to handle this kind of scenario. Most easy and convenient way you could consider by using linq join or linq Enumerable which you can implement as following:
Sample Data:
var childList = new List<ChildTable>()
{
new ChildTable(){ Id =101,ChildName = "Child-A",CustomerId = 202},
new ChildTable(){ Id =102,ChildName = "Child-B",CustomerId = 203},
new ChildTable(){ Id =103,ChildName = "Child-C",CustomerId = 202},
new ChildTable(){ Id =104,ChildName = "Child-D",CustomerId = 204},
};
var parentList = new List<ParentTable>()
{
new ParentTable(){ Id =301,ParentName = "Parent-A",CustomerId = 202},
new ParentTable(){ Id =302,ParentName = "Parent-B",CustomerId = 202},
new ParentTable(){ Id =303,ParentName = "Parent-C",CustomerId = 203},
new ParentTable(){ Id =304,ParentName = "Parent-D",CustomerId = 205},
};
Linq Query:
Way One:
var findMatchedByCustId = from child in childList
where (from parent in parentList select parent.CustomerId)
.Contains(child.CustomerId)
select child;
Way Two:
var usingLinqJoin = (from parent in parentList
join child in childList on parent.CustomerId equals child.CustomerId
select parent).ToList().Distinct();
Output:
Note: If you need more information you could check our official document for Linq join and Linq Projction here.

How to pull one column from second table in Linq query with join

I have the following linq query that works fine, but I am wanting to pull one column (CompanyId) from context.Emps into the results along with the results from context.BillingProfiles. How would I modify the select (select prof) below to include said column?
var query = (from prof in context.BillingProfiles
join emp in context.Emps on prof.ID equals emp.ID
join grp in context.BillingGroups on prof.GroupID equals grp.GroupID
where (prof.EndDate == null) && (grp.System == "sysGrp") && (prof.ID == id)
select prof).Distinct()
.Select(x => new OpId()
{
id = x.ID,
GroupId = x.GroupID,
OpId = x.OpID,
StartDate = x.StartDate,
EndDate = x.EndDate,
AddedOn = x.AddedOn,
AddedBy = x.AddedBy,
RemovedOn = x.RemovedOn,
RemovedBy = x.RemovedBy,
Prodid = x.ProdID,
});
Thanks
Project an anonymous object containing those too:
var query = from prof in context.BillingProfiles
join emp in context.Emps on prof.ID equals emp.ID
join grp in context.BillingGroups on prof.GroupID equals grp.GroupID
where prof.EndDate == null && prof.ID == id && grp.System == "sysGrp"
select new { prof, emp.CompanyId, grp };

Grouping by ID and displaying the top 1 with Linq

Looking for a bit of advice on grouping with entity framework and linq.
So i have a table "tbl_ChatLog" that contains userID and sendToUserID etc...and with this data i'm trying to display the "Top 1" from each "SendToUserID"
So in my UI it would look like so:
1001 (Contains multiple but show the top 1)
1003 (Contains multiple but show the top 1)
1008 (Contains multiple but show the top 1)
1009 (Contains multiple but show the top 1)
The start of my code below:
public static List<Chat> getChatMessage()
{
var entities = new FreeEntities();
//My ID
Business.User user = Business.User.getUserBySecurityToken();
List<Chat> chatMessages =
(
from cm in entities.tbl_ChatLog
where cm.UserID == user.uid
select new Chat
{
uid = (int)cm.UserID,
sendToUserID = (int)cm.SendToUserID,
message = cm.Message, dateAdded = (DateTime)cm.DateAdded
}
).OrderByDescending(x => x.dateAdded).ToList();
return chatMessages;
}
Hoping you can help me out on this one. Grouping always seems to throw me.
Much appreciated,
Terry
You could use groupby:
List<Chat> chatMessages =
(from cm in entities.tbl_ChatLog
where cm.UserID == user.uid
orderby cm.DateAdded descending
group cm by cm.sendToUserID into grp
select new Chat
{
uid = grp.FirstOrDefault().UserID,
sendToUserID = grp.Key,
message = grp.FirstOrDefault().Message,
dateAdded = grp.FirstOrDefault().DateAdded
}).ToList()
This will get you a list of your table data grouped by sendToUserID and the first entry of each group containing every property including sendToUserID.
The original problem was trying to select the first message from each unique "SendToUserId" and grouping by UserId and then selecting into a DTO was a nightmare but i managed to get a simple work around. Code below:
getFirstChatMessage()
{
var entities = new FreeEntities();
//User ID
Business.User user = Business.User.getUserBySecurityToken();
// Create new list of Chat
List<Chat> chatList = new List<Chat>();
var res = from c in entities.tbl_ChatLog
where c.UserID == user.uid
group c by c.UserID
into groups
select groups.OrderByDescending(p => p.DateAdded).FirstOrDefault();
foreach (var r in res)
{
chatList.Add(new Chat()
{
uid = (int)r.UserID,
sendToUserID = (int)r.SendToUserID,
message = (from m in entities.tbl_ChatLog where m.UserID == (int)r.SendToUserID
orderby r.DateAdded descending select m.Message).FirstOrDefault(),
dateAdded = (DateTime)r.DateAdded,
fullName = (from b in entities.tbl_Bio where b.UserID == (int)r.SendToUserID
select b.FirstName + " " + b.SurName).FirstOrDefault()
});
}
return chatList;
}

Select Values from two tables using Linq

Hi I know this has been asked plenty of times, I'm not getting it through my skull
How to select Values from several tables
I made these two Linq queries
First
r = (from d in db.stageManagers
where d.profileID == UserID && d.verticalID == VerticalID
select new StageModels()
{
UserId = d.profileID,
VerticalId = (int)d.verticalID,
VerticalStageID = d.stageID
}).FirstOrDefault();
Second
r = (from d in db.stageManagerVerticals
where d.ID == r.VerticalId
select new StageModels()
{
VerticalName = d.verticalName
}
).FirstOrDefault();
I want to make them one statement since they add data to one model and the tables they query have a Pk Fk relationship
In the first block d.verticalId is what I use to get the value(Name) in the secondblock, d.verticalId is primary key to stageManagerVerticals and foreign key in stageManager, How can i join these queries ?
I tried this:
r = (from d in db.stageManagers
join c in db.stageManagerVerticals on d.stageID equals c.ID
where d.profileID == UserID && d.verticalID == VerticalID
select new StageModels()
{
UserId = d.profileID,
VerticalId = (int)d.verticalID,
VerticalStageID = d.stageID;
VerticalName = c.verticalName
}
).FirstOrDefault();
try with JOIN in LINQ to select values from more than one table
eg:
var innerJoinQuery =
from category in categories
join prod in products on category.ID equals prod.CategoryID
select new { ProductName = prod.Name, Category = category.Name };
var leftOuterJoin=(c in categories
join p in products on c.ID equals p.CategoryID into t
from temp in t.DefaultIfEmpty()
select new { ProductName = p.Name, Category = c.Name }
).ToList();
You can utilize the Navigational Properties,
var r = db.stageManagers.Where(x => x.profileID == UserID && x.verticalID == VerticalID).
Select(
d => new StageModels() {
UserID = d.profileID,
VerticalID = (int)d.verticalID,
VerticalStageID = d.stageID,
VerticalName = d.stageManagerVertical.verticalName
}
).FirstOrDefault();

Syntax for "and" and distinct operation in entity framework?

I want to display the records whose accountid, id are matching and also display distinct records.
var result = from a in cxt.tblInventoryProducts
where a.aid == accID && a.id == id
select new
{
a.productType,
a.productName
};
Thanks in advance
Something like
var result = from a in cxt.tblInventoryProducts
where a.aid == accID && a.id == id
group a by new { a.productType, a.productName } into grp
select new
{
grp.Key.productType,
grp.Key.productName
};

Categories

Resources