2015-11-16 30 views
2

我正在玩新的ASP.Net 5.0 WebApi並努力瞭解如何返回多個子對象或孩子的孩子。如何包含多個子對象?

可以說我有4類:

public class Car 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
    public int TypeId { get; set; } 
    public int ColourId { get; set; } 

    public virtual Type Type { get; set; } 
    public virtual Colour Colour { get; set; } 
} 

public class Type 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
    public int TypeGroupId { get; set; } 

    public virtual TypeGroup TypeGroup { get; set; } 
} 

public class Colour 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
} 

public class TypeGroup 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
} 

,並想返回所有的數據對於汽車,包括類型,顏色,甚至類型的TypeGroup。我該怎麼做?

當我做這樣它僅包括類型:

[HttpGet] 
    public IEnumerable<Car> Get() 
    { 
     return _dbContext.Cars.Include(c => c.Type); 
    } 

這是我的設置在Startup.cs:

services.AddMvc().AddJsonOptions(options => 
     { 
      options.SerializerSettings.ContractResolver = 
       new CamelCasePropertyNamesContractResolver(); 
      options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; 
     }); 

是否有可能設置返回每一個孩子對象和孫子和等等?

非常感謝

+0

你可以爲每個導航屬性鏈接'Include()'。 – Ric

+0

但是如果我會有30個孩子,我將不得不這樣做30次?或者有沒有辦法將其設置爲包括所有? – Whistler

+1

您可以使用下列命令關閉所有實體的lazyloading:'this.Configuration.LazyLoadingEnabled = false;'參見[延遲加載](http://www.entityframeworktutorial.net/EntityFramework4.3/lazy-loading-with-dbcontext的.aspx)。您也可以從屬性聲明中刪除'virtual'/ – Ric

回答

3

您可以使用您的DbContext級以下(的地方這在構造函數)關閉延遲加載所有實體:

this.Configuration.LazyLoadingEnabled = false;

這將禁用所有實體 - 所以要謹慎,注意性能問題。

您可以加載特定類的所有實體的另一種方法是從屬性聲明中刪除virtual關鍵字。