Andy Evans
Andy Evans

Reputation: 7176

LINQ Join Errors

I'm getting the following error:

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

when using the code below

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

What I'm trying to do in LINQ is create a multi-condition join and am running into problems. Any ideas?

Thanks,

Upvotes: 2

Views: 374

Answers (1)

diceguyd30
diceguyd30

Reputation: 2752

Try giving names to the properties in your anonymous objects:

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

EDIT: Alright, I have to confess, I am no expert on query syntax, but you want to filter the 'items' list before doing the join, like the following fluent version of your query:

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)

ANOTHER EDIT: Per Ahmad's suggestion:

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

YET ANOTHER EDIT: Per another Ahmad suggestion:

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

Upvotes: 3

Related Questions