Odata $ expand不适用于特定查询

时间:2019-05-06 21:11:56

标签: c# asp.net-core odata

我们正在为Web应用程序制作一个ASP.NET Core API,该API应该从使用Entity Framework的SQL Server数据库中获取用户列表(并扩展特定字段)。它可以起作用,直到我们在URL中指定我们想要的用户ID。

这是Startup类:

public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        private static IEdmModel GetEdmModel()
        {
            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
            builder.EntitySet<User>("Users");
            builder.EntitySet<Character>("Characters");
            return builder.GetEdmModel();
        }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<GaiumContext>(opts => opts.UseSqlServer(Configuration["ConnectionString:Gaium"]));
            services.AddOData();
            services.AddMvc(options =>
            {
                options.EnableEndpointRouting = false;
            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseMvc(b =>
            {
                b.EnableDependencyInjection();
                b.Select().Expand().Filter().OrderBy().MaxTop(100).Count();
                b.MapODataServiceRoute("api", "api", GetEdmModel());
            });
        }
    }

这里是DbContext

public class GaiumContext : DbContext
    {
        public GaiumContext(DbContextOptions<GaiumContext> options) : base(options)
        {
        }

        public DbSet<User> Users { get; set; }
        public DbSet<Character> Characters { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<User>().HasMany(c => c.Characters);
        }
    }

最后,控制器UsersController

public class UsersController : ODataController
    {
        private GaiumContext _context;

        public UsersController(GaiumContext context)
        {
            _context = context;
        }

        [EnableQuery]
        public IActionResult Get()
        {
            return Ok(_context.Users);
        }

        [EnableQuery]
        public IActionResult Get(long key)
        {
            return Ok(_context.Users.Find(key));
        }
    }

用户对象如下:

Users {
  id: int,
  name: string,
  Characters: [{
    id: int,
    name: String
  }]
}

这是对所有用户的查询:

GET: https://localhost:44323/api/users?$expand=Characters

在这种情况下,查询工作正常,我们确实收到了用户列表及其“字符”字段。

{"@odata.context":"https://localhost:44323/api/$metadata#Users","value":[{"Id":1,"Username":"Ok","Characters":[{"Id":1,"Name":"bigusernamesmoke"}]}]}

但是,当我们尝试使用一个特定用户的ID获得结果时,“字符”列表为空:

GET: https://localhost:44323/api/users/1?$expand=Characters
{"@odata.context":"https://localhost:44323/api/$metadata#Users/$entity","Id":1,"Username":"Ok","Characters":[]}

1 个答案:

答案 0 :(得分:0)

请注意,Find(key)方法将返回单个 Book而不是可查询的对象:

  

返回Ok(_context.Users.Find(key));

如果我更改您的代码以返回 SingleResult ,如下所示:

[EnableQuery]
public SingleResult<User> Get(long key)
{
    var query = _context.Users.Where(p => p.Id == key);
    return SingleResult.Create(query);
}

对我来说很好。