I've just started to trying to build some test ASP.Net Web API app, and got a problem:
I have models as:
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; }
}
and trying to get all records from db via
public IEnumerable<Asset> GetAssets()
{
return db.Assets.AsEnumerable();
}
I get some strange results (atleast that's strange for me). Instead of expanding AssetType - I get nil's:
<Asset>
<AssetTypeId>1</AssetTypeId>
<Id>1</Id>
<AssetType i:nil="true"/>
</Asset>
I've checked my db - it contains correct IDs in both AssetTypeId and AssetType fields, pointing to correct asset type. The only way I've found to get fields expanded - is by changing GetAssets to:
public HttpResponseMessage GetAssets()
{
return Request.CreateResponse(HttpStatusCode.OK, db.Assets.Include("Type").ToList());
}
But I feel I'm very wrong, because in reality I have dozens of such 'complex' fields with some of them nested, and adding them via ".Include("Type")" - is wrong.
So the question is - where I've made an error? How can I get my data correctly?