문제

LINQ to SQL 문을 작성 중인데 다음과 같은 일반 내부 조인에 대한 표준 구문을 따르고 있습니다. ON C#의 절.

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 가입 운영자:

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 가입하다 연산자는 SQL에 아무런 이점을 제공하지 않습니다.즉.다음 쿼리

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

SQL에서 INNER 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();

원하는 테이블 이름을 작성하고 선택을 초기화하여 필드 결과를 가져옵니다.

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_Emp 그리고 TBL_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}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top