我剛開始試圖建立一些測試ASP.Net的Web API的應用程序,並得到了一個問題:ASP.Net的Web API返回null而不是非簡單屬性
我有型號爲:
public class Asset
{
public int Id { get; set; }
[ForeignKey("AssetType")]
public int AssetTypeId { get; set; }
public AssetType AssetType { get; set; }
}
public class AssetType
{
public int Id { get; set; }
public string Name { get; set; }
}
,並試圖通過
public IEnumerable<Asset> GetAssets()
{
return db.Assets.AsEnumerable();
}
從數據庫獲取的所有記錄,我得到一些奇怪的結果(ATLEAST這對我來說很奇怪)。而是擴大AssetType的 - 我得到零的:
<Asset>
<AssetTypeId>1</AssetTypeId>
<Id>1</Id>
<AssetType i:nil="true"/>
</Asset>
我檢查我的數據庫 - 它包含兩個AssetTypeId和AssetType領域正確的ID,指向正確的資產類型。 我發現得到擴大領域唯一的辦法 - 通過改變GetAssets到:
public HttpResponseMessage GetAssets()
{
return Request.CreateResponse(HttpStatusCode.OK, db.Assets.Include("Type").ToList());
}
但我覺得我是非常錯誤的,因爲在現實中,我有幾十個這樣的「複雜」領域的一些它們嵌套,並通過「.Include(」Type「)」添加它們 - 是錯誤的。
所以問題是 - 我犯了一個錯誤?我如何正確獲取我的數據?
注意我相信你可以只使用'公共虛擬AssetType AssetType {獲得;組; }'但你需要小心有關ORM的N + 1問題http://stackoverflow.com/questions/97197/what-is-the-n1-selects-issue我個人厭惡ORM中的延遲加載。 – 2014-10-17 18:25:23