我需要做一个LINQ2DataSet查询,对多个字段(如

var result = from x in entity
join y in entity2 
       on x.field1 = y.field1 
and 
          x.field2 = y.field2

我还没有找到一个合适的解决方案(我可以在where子句中添加额外的约束,但这远远不是一个合适的解决方案,或者使用这个解决方案,但这假设了一个等价连接)。

在LINQ中是否可以在一个连接中连接多个字段?

EDIT

var result = from x in entity
             join y in entity2
             on new { x.field1, x.field2 } equals new { y.field1, y.field2 }

是我在上面假设等联时引用的解决方案。

进一步的编辑

为了回答批评,我原来的例子是一个等量连接,我承认,我目前的要求是一个等量连接,我已经采用了我上面提到的解决方案。

然而,我正在尝试了解我已经/应该使用LINQ的可能性和最佳实践。我将需要做一个日期范围查询连接与表ID很快,只是先发制人的问题,看起来我必须在where子句中添加日期范围。

一如既往,感谢所有的建议和意见


当前回答

var result = from x in entity1
             join y in entity2
             on new { X1= x.field1, X2= x.field2 } equals new { X1=y.field1, X2= y.field2 }

如果两个实体中的列名不同,则需要这样做。

其他回答

声明一个类(类型)来保存要连接的元素。在下面的例子中声明JoinElement

 public class **JoinElement**
{
    public int? Id { get; set; }
    public string Name { get; set; }

}

results = from course in courseQueryable.AsQueryable()
                  join agency in agencyQueryable.AsQueryable()
                   on new **JoinElement**() { Id = course.CourseAgencyId, Name = course.CourseDeveloper } 
                   equals new **JoinElement**() { Id = agency.CourseAgencyId, Name = "D" } into temp1
from d in db.CourseDispatches
                             join du in db.DispatchUsers on d.id equals du.dispatch_id
                             join u in db.Users on du.user_id equals u.id
                             join fr in db.Forumreports on (d.course_id + '_' + du.user_id)  equals  (fr.course_id + '_'+ fr.uid)

这对我很有用

var result = from x in entity
   join y in entity2 on new { x.field1, x.field2 } equals new { y.field1, y.field2 }

如果字段名在实体中不相同

var result = from x in entity
   join y in entity2 on 
          new {
                field1=   x.field1,
               field2 =  x.field2 
             } 
          equals
         new { 
                field1= y.field1,
                field2=  y.myfield
              }
select new {x,y});
var result = from x in entity
             join y in entity2
             on new { X1= x.field1, X2= x.field2 } equals new { X1=y.field1, X2= y.field2 }
             select new 
             {
               /// Columns
              };