odata v4,List<> 属性 没有展开

odata v4, List<> Property without expand

是否可以在 odata4 中创建如下模型:

    public class PuppyDogs
    {

        public string Name { get; set; }

        public virtual IList<Bone> Bones { get; set; }
    }

    public class Bone
    {
        public string ChewType { get; set; }

        public int Numberofchews { get; set; }        

    }

控制器class看起来像

public class PuppyDogController : ODataController
{
    List<PuppysDog> mydogs = new List<PuppysDog>();

    private PuppyDogController()
    {
        if (mydogs.Count == 0)
        {
            PuppysDog mydog = new PuppysDog();

            mydog.Name = "Fido";

            mydog.Bones = new List<Bone>()
            {
                new Bone{ ChewType = "Soft", Numberofchews=1 },
                  new Bone{ ChewType = "Hard", Numberofchews=2 }
            };

            mydogs.Add(mydog);
        }
    }

    [EnableQuery]
    public IQueryable<PuppysDog> Get()
    {
        return mydogs.AsQueryable();
    }
}

我可以在不使用展开的情况下包含 PuppyDogs 的骨骼 属性 吗?默认情况下,骨骼不会返回给客户端。

你的代码中有几处不清楚,例如,实体集 PuppyDogs 没有键,控制器中的命名约定有点连线等。使用以下代码,它可以工作完美,请看

PuppyDog.cs

public class PuppyDog
{
    [Key]
    public string Name { get; set; }

    public virtual IList<Bone> Bones { get; set; }
}

Bone.cs

public class Bone
{
    public string ChewType { get; set; }

    public int Numberofchews { get; set; }

}

PupyyDogsController.cs

public class PuppyDogsController : ODataController
{
     List<PuppyDog> mydogs = new List<PuppyDog>();

    private PuppyDogsController()
    {
        if (mydogs.Count == 0)
        {
            PuppyDog mydog = new PuppyDog();

            mydog.Name = "Fido";

            mydog.Bones = new List<Bone>()
            {
                new Bone {ChewType = "Soft", Numberofchews = 1},
                new Bone {ChewType = "Hard", Numberofchews = 2}
            };

            mydogs.Add(mydog);
        }
    }

    [EnableQuery]
    public IQueryable<PuppyDog> Get()
    {
        return mydogs.AsQueryable();
    }
}

WebApiConfig.cs

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        ODataConventionModelBuilder builder = new ODataConventionModelBuilder();

        builder.EntitySet<PuppyDog>("PuppyDogs");

        config.MapODataServiceRoute("odata", null, builder.GetEdmModel(), new DefaultODataBatchHandler(GlobalConfiguration.DefaultServer));
        config.EnsureInitialized();
    }
}

然后当尝试http://localhost:21830/PuppyDogs时,我可以成功获得

的有效负载
{
    "@odata.context": "http://localhost:21830/$metadata#PuppyDogs",
    "value": [
     {
      "Name": "Fido",
      "Bones": [
         {
           "ChewType": "Soft",
           "Numberofchews": 1
         },
         {
           "ChewType": "Hard",
           "Numberofchews": 2
         }  
        ]
       }
     ]
}