Type inference failed in the call to 'Join'

2019-06-22 06:20发布

I have a peculiar problem with LINQ to SQL:

Doing this is fine:

from s in Something
join a in AnotherThing
on s.NullableDateTime.Value
equals a.DateTime
select s

However, using anonymous type like so:

from s in Something
join a in AnotherThing
on new { s.NullableDateTime.Value }
equals new { a.DateTime }
select s

Results in

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

I need to use anonymous types as I aim to add another column to join on.

Any ideas as to why this is occurring and how to fix?

1条回答
在下西门庆
2楼-- · 2019-06-22 07:15

You should tell to compiler, what properties it must compare:

 on new { s.NullableDateTime.Value }
 equals new { Value = a.DateTime }

The first creates an anonymous type, which looks like this:

class A
{
    public DateTime Value { get; set; }
}

The second line in your sample creates another anonymous type:

class B
{
    public DateTime DateTime { get; set; }
}

Hence, compiler can't understand, that you want to compare a.Value with b.DateTime.

查看更多
登录 后发表回答