Joe*_*Joe 5 c# linq linqpad linq-to-sql
鉴于我有三张桌子,车辆,汽车,自行车.汽车和自行车都有车辆ID FK,可以链接到车辆.
我想要计算所有像这样的汽车.
Vehicles.Select(x=>x.Car).Count();
Run Code Online (Sandbox Code Playgroud)
但是,这将为我提供所有车辆行,并在车辆类型为自行车的行中放置空值.
我正在使用linqpad执行此操作并查看sql语句我意识到它之所以这样做是因为在x.Car连接时它在车辆和汽车之间执行LEFT OUTER JOIN,这意味着它将返回所有车辆.如果我将查询更改为只使用JOIN,那么它按预期工作.
有没有办法告诉linq使用这种语法进行连接?最终我想做的事情如下:
Vehicles.Select(x=>x.Car.CountryID).Distinct().Dump();
Run Code Online (Sandbox Code Playgroud)
但是由于这个错误:
InvalidOperationException: The null value cannot be assigned to a member with type System.Int32 which is a non-nullable value type.
Run Code Online (Sandbox Code Playgroud)
我最终这样做了:
Vehicles.Where(x=>x.Car!=null).Select(x=>x.Car.CountryID).Distinct().Dump();
Run Code Online (Sandbox Code Playgroud)
好吧,该Where条款似乎是合理的,或者你可以使用实际的连接,假设你有一个CarID属性或类似的东西:
Vehicles.Join(Cars, v => v.CarID, c => c.ID, (v, c) => c.CountryID).Distinct()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
472 次 |
| 最近记录: |