Мы создаем ASP.NET Core API для веб-приложения, которое должно получать список пользователей (и расширять определенное поле) из базы данных SQL Server с Entity Framework.Он работает до тех пор, пока мы не укажем, какой идентификатор пользователя нам нужен в URL.
Вот класс 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":[]}