Vivek Patel
Vivek Patel

Reputation: 359

How to join 2 tables in LINQ to Entity?

I have 2 tables.

TableA :- ID, Name, Type
TableB :- ID, Name, TableAID

I want to Get the result list with the columns that includes TableA.Name, TableB.Name. I am using Entity Framework. Currently this is how i get data from Table1A.

IEnumerable<TableAModel> tableAData = DatabaseContext.FromContext().DatabaseName.TableA.AsEnumerable().Select(tableAData => tableAData.ToModel());

I want to create the same list which also includes the TableB.Name so i can have that display in my Grid? Is it possible?

Please let me know how to do this?

Upvotes: 0

Views: 1929

Answers (3)

Ralf de Kleine
Ralf de Kleine

Reputation: 11734

Something like this:

var db = DatabaseContext.FromContext();
var result = (from a in db.TableA 
              join b in db.TableB on a.ID equals b.TableAID 
              select new {
                  AID = a.ID, 
                  AName = a.Name, 
                  AType = a.Type, 
                  BName = b.Name}).ToList();

Ref: join clause (C# Reference)

Upvotes: 3

ForbesLindesay
ForbesLindesay

Reputation: 10702

You want something like this, but I don't know the exact result you want to achieve so it's hard to say precisely.

var db = DatabaseContext.FromContext().DatabaseName;
var AllData = from A in db.TableA
              from B in db.TableB
              where A.ID == B.TableAID
              select new {A,B};
var Result = AllData.AsEnumerable().Select(dat=>new{A=dat.A.ToModel(),B=dat.B.ToModel()});

Upvotes: 0

Etch
Etch

Reputation: 3054

A simple search on google has numerous examples. Here was one off the first page. Link

Upvotes: 1

Related Questions