我正在编写一个LINQ到SQL语句,并且我在c#中使用ON子句的正常内部连接的标准语法之后。
如何在LINQ to SQL中表示以下内容:
select DealerContact.*
from Dealer
inner join DealerContact on Dealer.DealerID = DealerContact.DealerID
我正在编写一个LINQ到SQL语句,并且我在c#中使用ON子句的正常内部连接的标准语法之后。
如何在LINQ to SQL中表示以下内容:
select DealerContact.*
from Dealer
inner join DealerContact on 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
};
其他回答
它是这样的:
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;
既然你要找的是联系人,而不是经销商。
使用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
};
基本上LINQ连接操作符对SQL没有好处。例如,下面的查询
var r = from dealer in db.Dealers
from contact in db.DealerContact
where dealer.DealerID == contact.DealerID
select dealerContact;
将导致内部连接在SQL
join对IEnumerable<>有用,因为它更有效:
from contact in db.DealerContact
条款将对每个经销商重新执行 但对于IQueryable<>则不是这样。另外,连接也不太灵活。
使用Linq Join操作符:
var q = from d in Dealer
join dc in DealerConact on d.DealerID equals dc.DealerID
select dc;
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();