I am very new to linq query so I need to join multiple tables and single output using Entity Framework mvc5
Below is my 3 table structures and Table_Application is a main table
1) Table_Application
Id ApplicationName ServiceId ProductID 1 Myapp 1 1
2) Table_Service
ServiceId SName 1 S1
3) Table_Product
ProductID PName 1 P1
I need linq out result data in linq list base on Table_Application ID
ApplicationName SName PName Myapp S1 P1
my sql query some thing like that
select t1.ApplicationName,t2.SName,t3.PName from Table_Application t1,Table_Service t2,Table_Product t3 where t1.ServiceId =t2.ServiceId and t1.ProductID=t3.ProductID and t1.Id="mysessionid"
I tried for single table coming but not able to join Table_Service and Table_Product
var IA = db.Applications .Where(x => x.ID == Id) .Select(IAview => new IAViewModel { ApplicationName = IAview.ApplicationName }).ToList();
Advertisement
Answer
Take a look at the LINQ query syntax – it’s similar to SQL so can be easier to understand if you’re coming from that sort of background.
There’s a tutorial on http://www.tutorialsteacher.com/linq/linq-query-syntax which will give you a basic starting point, then you can just add in joins etc as required.
Note that the following is untested and will give you a list of IAViewModel objects, but I think you would want something similar to the following:
var a = (from app in db.Applications join service in db.Services on app.ServiceId equals service.ServiceId join product in sb.Products on app.ProductId equals product.ProductId where app.Id == session_id select new IAViewModel { ApplicationName = app.ApplicationName, ServiceName = service.SName, ProductName = product.PName }).ToList();
If you only want a single result out of it, you can leave out the .ToList()
and instead use something like .FirstOrDefault()