Linq,如何 select 即使连接表中存在空值,C# windows 形式
Linq, How to select even where there is null in joined tables , C# windows form
我有车 table 和车主 table。我想在 DataGridView 中显示它们。但我的代码仅在 Owner 字段不为空时显示。我想显示所有这些
这是我的代码,也许你看到代码会更好地理解:
var cars = (from u in db.cars
join o in db.Owner on u.OwnerId equals o.OwnerId
order by u.carId
select new
{
CarId = u.CarId,
CarName = u.CarName,
OwnerName = o.FirstName +" "+ o.FirstName, // Here I want to display owner name or Empty if there is no owner
}).ToList();
dgvCars.DataSource = cars;
我哪里做错了?我应该如何编写代码? u.OwnerId 在我的 table 中可以为空。现在只显示拥有车主的汽车。但我什至想显示没有车主且车主姓名为 emptu 的汽车。提前致谢!
将查询更改为此,您需要外连接:
var cars = (from u in db.cars
join o in db.Owner on u.OwnerId equals o.OwnerId into oj
from o in oj.DefaultIfEmpty()
order by u.carId
select new
{
CarId = u.CarId,
CarName = u.CarName,
OwnerName = o.FirstName==null || o.LastName==null ?"": o.FirstName +" "+ o.LastName,
}).ToList();
var cars = (from u in db.cars
join o in db.Owner on u.OwnerId equals o.OwnerId into r2
from r3 in r2.DefaultIfEmpty()
order by u.carId
select new
{
CarId = u.CarId,
CarName = u.CarName,
OwnerName = r3.FirstName +" "+ r3.FirstName, owner name or Empty if there is no owner
}).ToList();
dgvCars.DataSource = cars;
我有车 table 和车主 table。我想在 DataGridView 中显示它们。但我的代码仅在 Owner 字段不为空时显示。我想显示所有这些 这是我的代码,也许你看到代码会更好地理解:
var cars = (from u in db.cars
join o in db.Owner on u.OwnerId equals o.OwnerId
order by u.carId
select new
{
CarId = u.CarId,
CarName = u.CarName,
OwnerName = o.FirstName +" "+ o.FirstName, // Here I want to display owner name or Empty if there is no owner
}).ToList();
dgvCars.DataSource = cars;
我哪里做错了?我应该如何编写代码? u.OwnerId 在我的 table 中可以为空。现在只显示拥有车主的汽车。但我什至想显示没有车主且车主姓名为 emptu 的汽车。提前致谢!
将查询更改为此,您需要外连接:
var cars = (from u in db.cars
join o in db.Owner on u.OwnerId equals o.OwnerId into oj
from o in oj.DefaultIfEmpty()
order by u.carId
select new
{
CarId = u.CarId,
CarName = u.CarName,
OwnerName = o.FirstName==null || o.LastName==null ?"": o.FirstName +" "+ o.LastName,
}).ToList();
var cars = (from u in db.cars
join o in db.Owner on u.OwnerId equals o.OwnerId into r2
from r3 in r2.DefaultIfEmpty()
order by u.carId
select new
{
CarId = u.CarId,
CarName = u.CarName,
OwnerName = r3.FirstName +" "+ r3.FirstName, owner name or Empty if there is no owner
}).ToList();
dgvCars.DataSource = cars;