我在使用EF 6和Linq保存和檢索相關記錄時遇到了一些麻煩。相關字段爲空的Linq查詢
我有兩個相關的實體,車輛和交易。在輸入交易時,用戶在保存交易之前從組合框中選擇車輛。車輛不是交易的必填字段,有時交易沒有相關車輛。目前,我正在使用以下代碼檢查組合框是否爲空,然後嘗試將車輛添加到事務中。
if (!string.IsNullOrEmpty(row.Cells[3].FormattedValue as String))
{
// A truck has been selected
int iSelectedVehicle;
if (int.TryParse(row.Cells[3].Value.ToString(), out iSelectedVehicle))
{
oTransaction.Vehicle = db.Vehicles.First(v => v.ID == iSelectedVehicle);
}
}
這似乎是工作好,直到我嘗試使用LINQ查詢檢索交易。當執行查詢時,我得到
"Object reference not set to an instance of an object."
因爲Vehicle字段爲空。我該如何處理這種情況?我試圖將Transaction中的Vehicle字段標記爲空,但由於它是虛擬字段,因此它不起作用,我得到一個錯誤「類型Vehicle必須是非空值....」
這是我的模型看起來像(略):
public class Transaction
{
[Key]
public int ID { get; set; }
...
public virtual Vehicle Vehicle { get; set; }
...
}
public class Vehicle
{
[Key]
public int ID { get; set; }
[Required]
[Index]
public int VehicleNumber { get; set; }
...
}
這裏是我的查詢:
var transactions = (from t in db.Transactions.AsEnumerable()
select new
{
Product = t.Product.ProductCode,
Description = t.Product.Description,
Transaction_Type = t.TransactionType.AddRemove,
Quantity = t.TransactionType.AddRemove == "Addition"
? t.FullQuantity + (t.PartialQuantity/t.Product.Pieces)
: -1 * (t.FullQuantity + (t.PartialQuantity/t.Product.Pieces)),
//Truck = t.Vehicle.VehicleNumber.ToString() ?? string.Empty, // This is the error line. I was trying to check for null but...
POJob = t.SourceNumber,
Transaction_Date = t.TransactionDate,
RecordedBy = t.User.Name,
RecordedDate = t.CreateDate
}).ToList();
看起來這將是一個相當普遍的情況,但我似乎無法得到解決它。
我對Windows Forms使用Code First。
var transactions = (from t in db.Transactions.DefaultIfEmpty()
select new
{
Product = t.Product.ProductCode,
Description = t.Product.Description,
Transaction_Type = t.TransactionType.AddRemove,
Quantity = t.TransactionType.AddRemove == "Addition"
? t.FullQuantity + (t.PartialQuantity/t.Product.Pieces)
: -1 * (t.FullQuantity + (t.PartialQuantity/t.Product.Pieces)),
Truck = t.Vehicle == null ? string.Empty : t.Vehicle.VehicleNumber.ToString(),
POJob = t.SourceNumber,
Transaction_Date = t.TransactionDate,
CreatedBy = t.CreatedBy.Name,
CreatedDate = t.CreateDate,
LastUpdatedBy = t.LastUpdatedBy.Name,
LastUpdated = t.LastUpdatedDate,
}).ToList();
這產生了不同的錯誤:
UPDATE
基於下面菲利普·史密斯的回答修訂的查詢。{「該函數的指定的參數值是無效的[參數#= 2,的函數名(如果已知的話)=的情況下]「}
因此,如果'Transaction'對象的'Vehicle'屬性爲null,你要跳過那個紀錄?你*可以得到'類型車輛必須是不可空值',因爲你已經將它設置爲'Required'。 –
我仍然想要檢索記錄,但車輛字段爲空。我需要VehicleNumber,但這是在Vehicle模型中,而不是在交易模型中。 – mack