Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

inner join in linq to entities

I have entity called Customer and it has three properties:

public class Customer {     public virtual Guid CompanyId;     public virtual long Id;     public virtual string Name; } 

I have also entity called Splitting and it has three properties:

public class Splitting {     public virtual long CustomerId;     public virtual long Id;     public virtual string Name; } 

Now I need to write a method that gets companyId and customerId. The method should return list of splitting that relates to the specific customerId in the companyId. Something like this:

public IList<Splitting> get(Guid companyId, long customrId) {         var res=from s in Splitting              from c in Customer              ...... how to continue?      return res.ToList(); } 
like image 643
Naor Avatar asked May 30 '11 12:05

Naor


People also ask

How use inner join in LINQ query?

A simple inner join that correlates elements from two data sources based on a simple key. An inner join that correlates elements from two data sources based on a composite key. A composite key, which is a key that consists of more than one value, enables you to correlate elements based on more than one property.

Is LINQ join inner or outer?

One commonly used feature of Language-Integrated Query (LINQ) is the facility to combine two sequences of related data using joins. The standard join operation provides an inner join but with a minor modification can be changed to give a left outer join.

Which join is valid in LINQ?

LINQ Inner Join Inner Join produces the result from two or more than two tables. So, basically we are meant to get the records from both tables based on matching conditions. Basically in SQL, we use the INNER JOIN keyword to make relationship between both tables. The following is the Linq query for above SQL query.


2 Answers

var res = from s in Splitting            join c in Customer on s.CustomerId equals c.Id          where c.Id == customrId             && c.CompanyId == companyId         select s; 

Using Extension methods:

var res = Splitting.Join(Customer,                  s => s.CustomerId,                  c => c.Id,                  (s, c) => new { s, c })            .Where(sc => sc.c.Id == userId && sc.c.CompanyId == companId)            .Select(sc => sc.s); 
like image 198
manji Avatar answered Sep 16 '22 16:09

manji


You can find a whole bunch of Linq examples in visual studio. Just select Help -> Samples, and then unzip the Linq samples.

Open the linq samples solution and open the LinqSamples.cs of the SampleQueries project.

The answer you are looking for is in method Linq14:

int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 }; int[] numbersB = { 1, 3, 5, 7, 8 };  var pairs =    from a in numbersA    from b in numbersB    where a < b    select new {a, b}; 
like image 30
RogierBessem Avatar answered Sep 16 '22 16:09

RogierBessem