2014-02-27 39 views
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; 

回答

0

您可以使用速記是這樣的(只要你不是在訪問導航屬性):

retval.OriginCity = oloc.City ?? string.Empty; 

您也可以通過存儲在變量重複訪問的值,使用對象使它更清潔初始值設定項:

//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(); 

     // Store variables that will be used repeatedly 
     string cityName = oloc.City ?? string.Empty; 
     string stateName = dloc.State == null ? string.Empty : dloc.State.StateName; 
     string countryName = dloc.Country == null ? string.Empty : dloc.Country.CountryName; 

     // Create object using object initializer and return 
     return new OrderInfo { 
      CreatedBy = o.User.UserName; 
      AccountName = o.Account.AccountName; 
      CustomerName = o.CustomerName; 
      OfficeName = o.Office.OfficeName; 
      DateCreated = o.DateCreated; 
      OriginCity = cityName; 
      OriginState = stateName; 
      OriginCountry = countryName; 
      AccountRef = o.AccountRefNumber; 
      DestinationCity = cityName; 
      DestinationState = stateName; 
      DestinationCountry = countryName; 
     }; 
    } 
    else 
    { 
     return new OrderInfo(); 
    } 
相關問題