0
Im填充POCO,我使用該POCO返回給調用者以便與綁定到控件一起使用,在Web表單上顯示等。如果其中一個實體爲空,那麼試圖讀取其相關實體值之一將導致異常。使用來自相關實體的值填充POCO對象,該值可能爲null,用於填充字符串
它的字段,如「DestinationState」,它可以在數據庫中爲空,但是我的POCO類將它定義爲一個字符串,不能將其定義爲可空。因此,就我而言,我對每個潛在問題都使用了一些測試,並將其設置爲空字符串。
下面是如何處理它。這工作,但似乎應該有更好的辦法?
OrderInfo retval = new OrderInfo();
//find order
Order o = ctx.Orders.Where(a => a.OrderId == oid).First();
if (o != null)
{
//now find the locations
Location oloc = o.Locations.Where(b => b.OrderKey == o.OrderId).Where(c => c.LocationType.TypeName == "Origin").FirstOrDefault();
Location dloc = o.Locations.Where(b => b.OrderKey == o.OrderId).Where(c => c.LocationType.TypeName == "Destination").FirstOrDefault();
retval.CreatedBy = o.User.UserName;
retval.AccountName = o.Account.AccountName;
retval.CustomerName = o.CustomerName;
retval.OfficeName = o.Office.OfficeName;
retval.DateCreated = o.DateCreated;
retval.OriginCity = oloc.City == null ? "" : oloc.City;
retval.OriginState = oloc.State == null ? "" : oloc.State.StateName;
retval.OriginCountry = oloc.Country == null ? "" : oloc.Country.CountryName;
retval.AccountRef = o.AccountRefNumber;
retval.DestinationCity = dloc.City == null ? "" : dloc.City;
retval.DestinationState = dloc.State == null ? "" : dloc.State.StateName;
retval.DestinationCountry = dloc.Country == null ? "" : dloc.Country.CountryName;
}
return retval;