gpt4 book ai didi

c# - linq to sql : specifying JOIN instead of LEFT OUTER JOIN

转载 作者:太空狗 更新时间:2023-10-29 23:10:46 25 4
gpt4 key购买 nike

鉴于我有三个表,Vehicles、Cars、Bikes。 Cars 和 Bikes 都有一个链接回 Vehicles 的 VehicleID FK。

我想计算所有这样的汽车。

Vehicles.Select(x=>x.Car).Count();

但是,这会给我 ALL 车辆行,并在车辆类型为 Bikes 的行中放入 null。
我正在使用 linqpad 来执行此操作并看到 sql 语句我意识到它这样做的原因是因为在 x.Car 连接上它在 vehicle 和 car 之间执行 LEFT OUTER JOIN 这意味着它将返回所有车辆。如果我将查询更改为仅使用 JOIN,那么它将按预期工作。

有没有办法告诉 linq 使用这种类型的语法进行连接?最终我想做这样的事情:

Vehicles.Select(x=>x.Car.CountryID).Distinct().Dump();

但是因为这个错误:

InvalidOperationException: The null value cannot be assigned to a member with type System.Int32 which is a non-nullable value type.

我最终这样做:

Vehicles.Where(x=>x.Car!=null).Select(x=>x.Car.CountryID).Distinct().Dump();

最佳答案

好吧,Where 子句似乎是合理的,或者您可以使用实际的连接,假设您有 CarID 属性或类似的东西:

Vehicles.Join(Cars, v => v.CarID, c => c.ID, (v, c) => c.CountryID).Distinct()

关于c# - linq to sql : specifying JOIN instead of LEFT OUTER JOIN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5535047/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com