2012-12-11 23 views
2

我在倉庫裏的方法來檢索項EF5和蘭巴/ LINQ的 - 如何只包含相關的表的一些列

public IQueryable<Item> GetAll() 
     { 
      //The following causes a circular reference if you attempt to serialize it via an API call. 
      IQueryable<Item> items = context.Items.Include(c => c.UserProfile).Include(c => c.UserProfile1).AsQueryable(); 
      return items; 
     } 

這出現問題的原因劍道電網和因爲我怎麼了系列化的所有記錄包括外部表用戶配置文件兩次,以便能夠獲取創建和修改項目記錄的用戶的全名。

而不是Include(c => c.UserProfile)有沒有辦法只包括UserProfile.FullName列?

今天我處理這在我的視圖模型,並創建一個新的子類(本例中是位置,而不是項目):

public class LocationsListViewModel 
    { 
     public IEnumerable<LocationsGrid> Locations { get; set; } 
     public IEnumerable<Facility> Facilities { get; set; } 
     public IEnumerable<string> AreaOptions { get; set; } 
     public int LocationCount { get; set; } 

     public class LocationsGrid 
     { 
      public int Id { get; set; } 
      public string DisplayLocation { get; set; } 
      public string Area { get; set; } 
      public string Zone { get; set; } 
      public string Aisle { get; set; } 
      public string Bay { get; set; } 
      public string Level { get; set; } 
      public string Position { get; set; } 
      public string Barcode { get; set; } 

     } 
    } 

,然後不得不填充,在我的任務或應用服務層(坐鎮控制器和存儲庫)這樣間:

viewModel.Locations = from l in locations.ToList() 
select new LocationsListViewModel.LocationsGrid 
{ 
    Id = l.Id, 
    DisplayLocation = l.DisplayLocation, 
    Area = l.Area, 
    Zone = l.Zone, 
    Aisle = l.Aisle, 
    Bay = l.Bay, 
    Level = l.Level, 
    Position = l.Position, 
    Barcode = l.BarcodeValue 
}; 
這似乎是很多額外的代碼和維護每個實體前進。我確信有一個更有效的方法來做到這一點。

+0

我知道你想問什麼,但我也有同樣的問題。如果只是做了db.Products.AsEnumerable(),那麼返回多個表,所以我做了匿名方法,並且對於所有前進的方法來說工作太多了。 – Mitul

+0

@ChadRichardson DTO的/ view模型重新做更多的工作(即AutoMapper或ValueInjecter可以減輕負擔),但最終還是要付出代價的。 –

回答

1

我通常使用數據傳輸對象(基本上只是有你要找的,然後從您的數據訪問方法返回該類型的對象的確切數據的類。

public IQueryable<ItemSummary> GetAll() 
    { 
     IQueryable<ItemSummary> items = context.Items 
      .Select(c => new ItemSummary { 
        FirstProfileName = c.UserProfile.FullName, 
        SecondProfileName = c.UserProfile1.FullName, 
        ScalarProp1 = c.ScalarProp1, 
        ... 
       }) 
      .AsQueryable(); 
     return items; 
    } 

我我不知道這是否會以你想要的方式工作,因爲我不熟悉Kendo Grid等,但它可能是有用的。

+0

是的,這就是我現在正在做的......我的MVC ViewModel是我的DTO。它只是很多額外的代碼來維護。感謝您的回覆。 –