let i have a candidate table in which few records are there and some other tables related to a candidate(one to many relation) i fetch a candidate from a table and based on the id i fetch records from other tables and each table has four to five or more rows in it.
so there is a bulk of data related to single candidate.
i want to know if i use linq to fetch records so what would be the query for fetching. i am designing the app in mvc pattern.
so i declare Ienumrable fields in my model to display records(lists) related to a specific candidate.
A test case:
db.candidates.where(i=>i.canid=someid).
can.academics=db.academics.where(a=>a.id==can.id).toList();
the academics would be displayed to view accordingly.further fields are also there, additionally candidate has its own data too.
i want to know that for a test case, is there any way i can join these two tables (or more)
can.tbl1= tbl1.GetListById(can.CanId).ToList();
can.tbl2 = tbl2.GetListById(can.CanId).ToList();
can.tbl3 = tbl3.GetListById(can.CanId).ToList();
can.tbl4= tbl4.GetListById(can.CanId).ToList();
Note:GetListById()could be any method.
my question is that is this a practical way to populate data or should i follow any other way
umair mohsinPosted Sep 30, 2024, 9:00 PM
thank you for your quick reply dear i have tried your linq join logic earlier but you are not returning any thing as you are binding variables under select new so eventually candidateData variable should be casted to ToList();
var data = (from a in context.GetModel()
join acad in acadContext.GetModel() on a.CanId equals acad.CanId
where a.Id == id
select new
{
can = a,
academics = acad
});
here is your approach and its returning nothing and here is mine but issue still exist in it
var data = (from a in context.GetModel()
join acad in acadContext.GetModel() on a.CanId equals acad.CanId
where a.Id == id
select new
{
can = a,
academics = acad
}).ToList();
when i debug my code it gives me data and academics have sames list of data as my DB.
i have to give academics to my model.academcs now this this is the main issue ican't do this.
please help me if you can solve it i also don't want to use these lines of code
Muhammad Imran AnsariPosted Sep 30, 2024, 6:20 PM
Hi Umair,
Your current approach of fetching data table by table is functional, it’s not optimal in terms of performance. You can load the data through either Eager loading (if using Entity Framework) using.Include() or joins in LINQ are better approaches for fetching related data in a single query, this approach is also reducing the number of database calls.