Programming

LINQ to SQL의 내부 조인 구문은 무엇입니까?

procodes 2020. 2. 18. 22:53
반응형

LINQ to SQL의 내부 조인 구문은 무엇입니까?


LINQ to SQL 문을 작성 중이며 ONC # 과 함께 일반적인 내부 조인에 대한 표준 구문을 따릅니다 .

LINQ to SQL에서 다음을 어떻게 표현합니까?

select DealerContact.*
from Dealer 
inner join DealerContact on Dealer.DealerID = DealerContact.DealerID

그것은 다음과 같습니다 :

from t1 in db.Table1
join t2 in db.Table2 on t1.field equals t2.field
select new { t1.field2, t2.field3}

더 나은 예를 위해 테이블에 적절한 이름과 필드를 갖는 것이 좋습니다. :)

최신 정보

나는 당신의 쿼리에 대해 이것이 더 적절할 것이라고 생각합니다.

var dealercontacts = from contact in DealerContact
                     join dealer in Dealer on contact.DealerId equals dealer.ID
                     select contact;

딜러가 아닌 연락처를 찾고 있기 때문에.


그리고 표현 체인 구문을 선호하기 때문에 다음과 같이 사용하십시오.

var dealerContracts = DealerContact.Join(Dealer, 
                                 contact => contact.DealerId,
                                 dealer => dealer.DealerId,
                                 (contact, dealer) => contact);

Clever Human 의 표현식 체인 구문 답변 을 확장하려면

함께 결합되는 두 테이블의 필드 (두 테이블 중 하나만)에서 필드 (필터 또는 선택)를 수행하려는 경우 Join 매개 변수의 최종 매개 변수에 대한 람다 식으로 새 객체를 만들 수 있습니다 예를 들어, 다음 두 테이블을 통합합니다.

var dealerInfo = DealerContact.Join(Dealer, 
                              dc => dc.DealerId,
                              d => d.DealerId,
                              (dc, d) => new { DealerContact = dc, Dealer = d })
                          .Where(dc_d => dc_d.Dealer.FirstName == "Glenn" 
                              && dc_d.DealerContact.City == "Chicago")
                          .Select(dc_d => new {
                              dc_d.Dealer.DealerID,
                              dc_d.Dealer.FirstName,
                              dc_d.Dealer.LastName,
                              dc_d.DealerContact.City,
                              dc_d.DealerContact.State });

흥미로운 부분은 해당 예제의 4 번째 줄에있는 람다 식입니다.

(dc, d) => new { DealerContact = dc, Dealer = d }

여기서는 모든 필드와 함께 DealerContact 및 Dealer 레코드를 속성으로 갖는 새로운 익명 유형 객체를 구성합니다.

그런 다음 예제의 나머지 부분에서 보여 dc_d주듯이 결과를 필터링하고 선택할 때 해당 레코드의 필드를 사용 하여 DealerContact 및 Dealer 레코드를 속성으로 갖는 익명 개체의 이름으로 사용 합니다.


var results = from c in db.Companies
              join cn in db.Countries on c.CountryID equals cn.ID
              join ct in db.Cities on c.CityID equals ct.ID
              join sect in db.Sectors on c.SectorID equals sect.ID
              where (c.CountryID == cn.ID) && (c.CityID == ct.ID) && (c.SectorID == company.SectorID) && (company.SectorID == sect.ID)
              select new { country = cn.Name, city = ct.Name, c.ID, c.Name, c.Address1, c.Address2, c.Address3, c.CountryID, c.CityID, c.Region, c.PostCode, c.Telephone, c.Website, c.SectorID, Status = (ContactStatus)c.StatusID, sector = sect.Name };


return results.ToList();

Linq Join 연산자를 사용하십시오 .

var q =  from d in Dealer
         join dc in DealerConact on d.DealerID equals dc.DealerID
         select dc;

외래 키를 만들고 LINQ-to-SQL은 탐색 속성을 만듭니다. Dealer그러면 각각 DealerContacts선택, 필터링 및 조작 할 수 있는 모음 이 있습니다.

from contact in dealer.DealerContacts select contact

또는

context.Dealers.Select(d => d.DealerContacts)

탐색 속성을 사용하지 않으면 LINQ-to-SQL의 주요 이점 중 하나 인 개체 그래프를 매핑하는 부분이 누락 된 것입니다.


기본적으로 LINQ join 연산자는 SQL에 이점이 없습니다. 즉 다음 쿼리

var r = from dealer in db.Dealers
   from contact in db.DealerContact
   where dealer.DealerID == contact.DealerID
   select dealerContact;

SQL에서 INNER JOIN이 발생합니다.

join 은 IEnumerable <>에 더 유용합니다.

from contact in db.DealerContact  

조항은 모든 딜러에 대해 다시 실행되지만 IQueryable <>의 경우에는 그렇지 않습니다. 또한 조인 이 덜 유연합니다.


실제로, 종종 linq에 참여하지 않는 것이 좋습니다. 탐색 속성이있는 경우 linq 문을 작성하는 매우 간결한 방법은 다음과 같습니다.

from dealer in db.Dealers
from contact in dealer.DealerContacts
select new { whatever you need from dealer or contact }

where 절로 변환됩니다.

SELECT <columns>
FROM Dealer, DealerContact
WHERE Dealer.DealerID = DealerContact.DealerID

내부 조인 을 수행 하려면 LINQ 조인사용하십시오 .

var employeeInfo = from emp in db.Employees
                   join dept in db.Departments
                   on emp.Eid equals dept.Eid 
                   select new
                   {
                    emp.Ename,
                    dept.Dname,
                    emp.Elocation
                   };

이 시도 :

     var data =(from t1 in dataContext.Table1 join 
                 t2 in dataContext.Table2 on 
                 t1.field equals t2.field 
                 orderby t1.Id select t1).ToList(); 

var q=(from pd in dataContext.tblProducts join od in dataContext.tblOrders on pd.ProductID equals od.ProductID orderby od.OrderID select new { od.OrderID,
 pd.ProductID,
 pd.Name,
 pd.UnitPrice,
 od.Quantity,
 od.Price,
 }).ToList(); 

OperationDataContext odDataContext = new OperationDataContext();    
        var studentInfo = from student in odDataContext.STUDENTs
                          join course in odDataContext.COURSEs
                          on student.course_id equals course.course_id
                          select new { student.student_name, student.student_city, course.course_name, course.course_desc };

학생과 코스 테이블에 기본 키와 외래 키 관계가있는 경우


대신 이것을 시도하십시오.

var dealer = from d in Dealer
             join dc in DealerContact on d.DealerID equals dc.DealerID
             select d;

var Data= (from dealer in Dealer join dealercontact in DealerContact on dealer.ID equals dealercontact.DealerID
select new{
dealer.Id,
dealercontact.ContactName

}).ToList();

var data=(from t in db.your tableName(t1) 
          join s in db.yourothertablename(t2) on t1.fieldname equals t2.feldname
          (where condtion)).tolist();

var list = (from u in db.Users join c in db.Customers on u.CustomerId equals c.CustomerId where u.Username == username
   select new {u.UserId, u.CustomerId, u.ClientId, u.RoleId, u.Username, u.Email, u.Password, u.Salt, u.Hint1, u.Hint2, u.Hint3, u.Locked, u.Active,c.ProfilePic}).First();

원하는 테이블 이름을 쓰고 필드 결과를 얻기 위해 선택을 초기화하십시오.


DealerContrac의 d1에서 d1.dealearid의 DealerContrac의 d2에 가입하면 d2.dealerid가 새 {dealercontract. *}를 선택합니다.


linq C #에서 내부 조인 두 테이블

var result = from q1 in table1
             join q2 in table2
             on q1.Customer_Id equals q2.Customer_Id
             select new { q1.Name, q1.Mobile, q2.Purchase, q2.Dates }

가장 좋은 예

테이블 이름 : TBL_EmpTBL_Dep

var result = from emp in TBL_Emp join dep in TBL_Dep on emp.id=dep.id
select new
{
 emp.Name;
 emp.Address
 dep.Department_Name
}


foreach(char item in result)
 { // to do}

참고 : https://stackoverflow.com/questions/37324/what-is-the-syntax-for-an-inner-join-in-linq-to-sql



반응형