【问题标题】:$expand in OData V4OData V4 中的 $expand
【发布时间】:2020-09-23 15:34:30
【问题描述】:

*更新: 能够follow this tutorial,现在我得到的错误状态是:

"message": "No HTTP resource was found that matches the request URI 'http://localhost:0000/api/v1/Pets('dog')/Color'."
      "message": "No routing convention was found to select an action for the OData path with template '~/entityset/key/unresolved'."

有什么想法吗?*

尝试使用 OData V4 在我的宠物查询中检索颜色时出现错误。 我遇到了很多麻烦,理想情况下我会使用颜色扩展(例如 localhost:0000/api/v1/Pets('dog')?$expand=Colors)

我需要返回的 JSON 类似于:

[
  {
    "_Key": "1",
    "animalname": "dog",
    "furcolorname": "black,white",
    "color": {
      "_Key": "1",
      "colorname": "black"
    },
    {
      "_Key": "2",
      "colorname": "white"
    }
  }
]

也许我走错了路,无论哪种方式都值得赞赏!

如果我查询 localhost:0000/api/v1/Pets('dog') :

…
"Message\": \"Invalid column name 'Pet__Key'.\"     
…

如果我查询 localhost:0000/api/v1/Pets('dog')?$exand=Colors :

…
"The query specified in the URI is not valid. Could not find a property named 'Colors' on type 'PetShop.Odata.Models.Pet'."    
…

Pet.cs 模型:

namespace PetShop.Odata.Models
{
   [Table("pet")]
   public class Pet
   {
      [Key]
      public string _Key { get; set; }
      public string AnimalName { get; set; }

      [ForeignKey("Color")]
      public string FurColorName { get; set; }
      public virtual Color Color { get; set; }

      public virtual ICollection<Color> Colors { get; set; }
   }
}

Color.cs 模型:

namespace PetShop.Odata.Models
{
   [Table("color")]
   public class Color
   {
      public Color()
      {
         new HashSet<Pet>();
      }

      [Key]
      public string _Key { get; set; }
      public string ColorName { get; set; }
   }
}

PetsController.cs:

namespace PetShop.Odata.Controllers
{
   [ApiVersion("1.0")]
   [ODataRoutePrefix("Pets")]
   [ApiControllerMetricReport]
   public class PetsController : ODataController
   {
      private readonly MyContext context = new MyContext ();

      [HttpGet]
      [ODataRoute]
      [EnableQuery]
      [ResponseType(typeof(List<Pet>))]
      public IHttpActionResult Get()
      {
         return Ok(context.Pets.AsQueryable());
      }

      [EnableQuery]
      public IQueryable<Color> Get ([FromODataUri] string key)
      {
         return context.Pets.Where(m => m._Key == key).SelectMany(a => a.Colors);
      }

      protected override void Dispose(bool disposing)
      {
         context.Dispose();
         base.Dispose(disposing);
      }
   }
}

ColorsController.cs:

namespace PetShop.Odata.Controllers
{
   [ApiVersion("1.0")]
   [ODataRoutePrefix("Colors")]
   [ApiControllerMetricReport]
   public class ColorsController : ODataController
   {
      private readonly MyContext context = new MyContext ();

      [HttpGet]
      [ODataRoute]
      [EnableQuery]
      [ResponseType(typeof(List<Color>))]
      public IHttpActionResult Get()
      {
         return Ok(context.Colors.AsQueryable());
      }

      protected override void Dispose(bool disposing)
      {
         context.Dispose();
         base.Dispose(disposing);
      }
   }
}

PetConfig.cs:

namespace PetShop.Odata.Configuration
{   public class PetModelConfiguration : IModelConfiguration
   {
      public void Apply(ODataModelBuilder builder, ApiVersion apiVersion)
      {
         builder.EntitySet<Pet>("Pets");
      }
   }
}

ColorConfig.cs:

namespace PetShop.Odata.Configuration
{   public class ColorModelConfiguration : IModelConfiguration
   {
      public void Apply(ODataModelBuilder builder, ApiVersion apiVersion)
      {
         builder.EntitySet<Color>("Colors");
      }
   }
}

MyContext.cs:

…
public DbSet<Pet> Pets { get; set; }
public DbSet<Color> Colors { get; set; }
…

Setup.cs:

…
public static HttpServer CreateHttpServer()
      {
         var httpConfig = new HttpConfiguration();
         var webApiServer = new HttpServer(httpConfig);

         httpConfig.AddApiVersioning(options => options.ReportApiVersions = true);

         httpConfig.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

         var modelBuilder = new VersionedODataModelBuilder(httpConfig)
         {
            ModelBuilderFactory = () => new ODataConventionModelBuilder().EnableLowerCamelCase(),

            ModelConfigurations =
          {
              new PetConfig(),
              new ColorConfig()
            },
         };
         var models = modelBuilder.GetEdmModels();

         httpConfig.Count().Filter().OrderBy().Expand().Select().MaxTop(null);
…

【问题讨论】:

    标签: c# odata odata-v4


    【解决方案1】:

    假设您使用的是默认路由约定,则 PetsController.cs 中的 Get colors 方法与预期的 OData 路由格式不匹配。

    而不是以下:

    [EnableQuery]
    public IQueryable<Color> Get ([FromODataUri] string key)
    {
       return context.Pets.Where(m => m._Key == key).SelectMany(a => a.Colors);
    }
    

    你应该试试:

    [EnableQuery]
    public IQueryable<Color> GetColors ([FromODataUri] string key)
    {
       return context.Pets.Where(m => m._Key == key).SelectMany(a => a.Colors);
    }
    

    此定义将使 OData 路由:http://localhost:0000/api/v1/Pets('dog')/Colors

    有关路由约定的更多信息,请参阅https://docs.microsoft.com/en-us/odata/webapi/built-in-routing-conventions

    还有几种替代方法:

    1. Register a different name to a custom nav property
    2. 定义自定义OData Function

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-27
      • 2015-07-29
      • 1970-01-01
      • 2015-04-24
      • 2017-02-27
      • 1970-01-01
      • 2019-12-02
      • 2015-02-15
      相关资源
      最近更新 更多