LINQ加入错误

时间:2010-11-02 17:59:15

标签: linq linq-to-sql join

我收到以下错误:

The type of one of the expressions in the join clause is incorrect.  Type inference failed in the call to 'Join'.

使用下面的代码时

var ccrCodes = (from c in db.CCRCodes
               join i in items on
                new { c.baan_cat_fam_code, c.baan_cat_code } equals
                new { i.baan_cat_family_code, i.baan_cat_code }
               where i => i.contact_dt.Value.Year == date.Year && i.contact_dt.Value.Month == date.Month
               select c).Distinct().OrderBy(c => c.code_desc);

我在LINQ中尝试做的是创建一个多条件连接并遇到问题。有什么想法吗?

谢谢,

1 个答案:

答案 0 :(得分:3)

尝试为匿名对象中的属性指定名称:

var ccrCodes = (from c in db.CCRCodes
               join i in items on
                new { FamCode = c.baan_cat_fam_code, CatCode = c.baan_cat_code } equals
                new { FamCode = i.baan_cat_family_code, CatCode = i.baan_cat_code }
               where i => i.contact_dt.Value.Year == date.Year && i.contact_dt.Value.Month == date.Month
               select c).Distinct().OrderBy(c => c.code_desc);

编辑:好吧,我必须承认,我不是查询语法方面的专家,但是你想在进行连接之前过滤'items'列表,就像下面的查询的流畅版本一样:

db.CCRCodes
    .Join(
        items.Where(i => i.contact_dt.Value.Year == date.Year && i.contact_dt.Value.Month == date.Month),
        x => new { FamCode = x.baan_cat_fam_code, CatCode = x.baan_cat_code },
        x => new { FamCode = x.baan_cat_family_code, CatCode = x.baan_cat_code },
        (o,i) => o
    ).Distinct().OrderBy(c => c.code_desc)

另一个编辑:Per Ahmad的建议:

var ccrCodes = (from c in db.CCRCodes
                   join i in items.Where(x => x.contact_dt.Value.Year == date.Year && x.contact_dt.Value.Month == date.Month) on
                    new { FamCode = c.baan_cat_fam_code, CatCode = c.baan_cat_code } equals
                    new { FamCode = i.baan_cat_family_code, CatCode = i.baan_cat_code }
                   select c).Distinct().OrderBy(c => c.code_desc);

另一个编辑:另一个艾哈迈德的建议:

var ccrCodes = (from c in db.CCRCodes
                from i in items
                where i.contact_dt.Value.Year == date.Year && i.contact_dt.Value.Month == date.Month 
                  && c.baan_cat_fam_code == i.baan_cat_family_code && c.baan_cat_code == i.baan_cat_code
                select c).Distinct().OrderBy(c => c.code_desc);