ChatGPT解决这个技术问题 Extra ChatGPT

LINQ to SQL 中的内部联接的语法是什么?

我正在编写一个 LINQ to SQL 语句,并且我正在使用 C# 中带有 ON 子句的普通内部连接的标准语法。

您如何在 LINQ to SQL 中表示以下内容:

select DealerContact.*
from Dealer 
inner join DealerContact on Dealer.DealerID = DealerContact.DealerID
如果表之间有外键,您应该在下面查看 Kirk Broadhurst 的答案。
@ANeves 使用复数表名远非标准做法,单数和复数都是完全可以接受的-我自己只是从复数切换到单数以匹配对象名称-这里的最佳答案同意单数更一致(许多复数形式很奇怪或非存在 - 例如“1 只羊,8 只羊”:stackoverflow.com/questions/338156/…
@niico 这不是讨论这个的地方,我猜...但是 Microsoft Entity Framework pluralizes the table names,Ruby on Rails 的 ORM pluralizes the tables...这对您来说是否足够接近标准实践? :) 反驳论点:NHibernate seems to not pluralize tables
确实-有些人以一种方式做事-有些人以另一种方式做事。没有标准做法。我个人认为单数有更多的好处。

J
Jon Limjap

它类似于:

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;

由于您正在寻找联系人,而不是经销商。


谢谢,从现在开始,我将使用 sensible names 作为最佳实践,这在 linq 中是有意义的,而不是 from c or from t1
我过去曾多次使用过 linq 连接,但遇到了一个我以前从未见过的问题,因为您在 VS 中看到的错误并不完全清楚:当您编写 ON 语句时,您必须引用 FROM 表第一的。你可以说 on t1.field equals t2.field 但你不能写 on t2.field equals t1.field 因为在这种情况下编译器不会理解 t2 指的是什么。
C
CleverPatrick

因为我更喜欢表达式链语法,所以你可以这样做:

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

如果您需要过滤或选择 both 联接表中的字段,而不仅仅是两个表之一(此答案示例中的 DealerContact 表)的字段,以下是一个示例:stackoverflow.com/a/29310640/12484
C
Community

要扩展 Clever Human 的表达式链语法 answer

如果您想对连接在一起的两个表中的字段执行操作(如过滤或选择)——而不是仅在这两个表中的一个上——您可以在 Join 方法的最终参数的 lambda 表达式中创建一个新对象合并这两个表,例如:

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 行中的 lambda 表达式:

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

...我们构造一个新的匿名类型对象,该对象具有 DealerContact 和 Dealer 记录的属性,以及它们的所有字段。

然后,我们可以在过滤和选择结果时使用这些记录中的字段,如示例的其余部分所示,该示例使用 dc_d 作为我们构建的匿名对象的名称,该对象具有 DealerContact 和 Dealer 记录作为其属性.


使用 lambda 的连接有糟糕的语法。我拒绝使用它;-)
@aristo 我一点也不怪你。我通常不得不参考这篇文章来提醒自己语法!
像我这样的人更喜欢一致性。这就是我专门搜索 lambda 语法的原因。
t
travis
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();

嗨,你能告诉我这部分是关于什么的吗? Status = (ContactStatus)c.StatusID 我对片段特别感兴趣:(ContactStatus)c.StatusID Regards Mariusz
@aristo - 查看代码,我猜 ContactStatus 确实是一个枚举,而 c.StatusID 并不是一个真正的 ID,而是枚举的数值。如果我是对的,(ContactStatus)c.StatusID 实际上只是将整数转换为枚举。
K
Kirk Broadhurst

您创建一个外键,LINQ-to-SQL 为您创建导航属性。然后,每个 Dealer 都会有一个 DealerContacts 集合,您可以对其进行选择、过滤和操作。

from contact in dealer.DealerContacts select contact

或者

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

如果您不使用导航属性,那么您将错过 LINQ-to-SQL 的主要优势之一 - 映射对象图的部分。


哦,伙计,你节省了我的时间,我不再需要处理这些愚蠢的连接了!
a
aku

使用 Linq Join 运算符:

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

当我想要 d 和 dc 的列时该怎么办?
@KuntadyNithesh 然后返回您创建的类,例如 select new MyCustomer{ Id = dc.id, Id2 = d.id } 就是这样!
t
the_joric

基本上 LINQ 连接运算符对 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<> 情况并非如此。连接也不太灵活。


G
Gert Arnold

实际上,在 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

具有多个“from”子句(如本例中)的 LINQ 查询在表达式链语法中是什么样的?可能吗?
其方法语法等价物是 SelectMany()
w
wazz

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 }

v
vzwick

使用 LINQ joins 执行内部联接。

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
                   };

A
Ajay

尝试这个 :

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

a
ammad khan
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(); 

欢迎来到堆栈溢出!虽然此代码段可能会解决问题,但 including an explanation 确实有助于提高帖子的质量。请记住,您正在为将来的读者回答问题,而这些人可能不知道您的代码建议的原因。也请尽量不要用解释性注释来拥挤你的代码,因为这会降低代码和解释的可读性!
S
Sandeep Shekhawat
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 };

学生和课程表具有主键和外键关系的位置


M
Milan

试试这个,

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

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

}).ToList();

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

A
Aryan Firouzian
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();

写下你想要的表名,初始化select得到字段的结果。


var list = (from u in db.Yourfirsttablename join c in db.secondtablename on u.firsttablecommonfields equals c.secondtablecommon field 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();
R
Rutu

从 DealerContrac 中的 d1 在 d1.dealearid 上加入 DealerContrac 中的 d2 等于 d2.dealerid 选择新的 {dealercontract.*}


欢迎来到堆栈溢出!这个答案对已经存在的答案没有任何增加。
J
JDB

一个最好的例子

表名: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}