I have a .NET 8 Blazor App. I want to use OData for CRUD. My database is code first, created with migrations.
For the following model:
public class Category
{
[Key]
public int Id { get; set; }
public string? Name { get; set; }
public ICollection<Expense>? Expenses { get; set; }
}
And the following DbContext:
public class MoneyMachineDbContext : DbContext
{
public MoneyMachineDbContext(DbContextOptions<MoneyMachineDbContext> options) : base(options)
{
}
public MoneyMachineDbContext()
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Category>()
.HasMany(c => c.Expenses)
.WithOne(e => e.Category);
modelBuilder.Entity<MonthReport>()
.HasMany(mr => mr.Expenses)
.WithOne(e => e.MonthReport);
}
public DbSet<MonthReport> MonthReports { get; set; }
public DbSet<Expense> Expenses { get; set; }
public DbSet<Category> Categories { get; set; }
}
And the following Restier configuration:
builder.Services.AddDbContextFactory<MoneyMachineDbContext>(options =>
options.UseSqlServer("Server=localhost\SQLEXPRESS;Database=MoneyMachine;Trusted_Connection=True;Integrated Security=true;TrustServerCertificate=true;"));
// Configure Restier OData
builder.Services.AddRestier(apiBuilder =>
{
apiBuilder.AddRestierApi<EntityFrameworkApi<MoneyMachineDbContext>>(services =>
{
services.AddEFCoreProviderServices<MoneyMachineDbContext>((serviceProvider, options) =>
{
options.UseSqlServer("Server=localhost\SQLEXPRESS;Database=MoneyMachine;Trusted_Connection=True;Integrated Security=true;TrustServerCertificate=true;");
});
services.AddSingleton<IChangeSetInitializer, DefaultChangeSetInitializer>();
});
});
...
app.Filter().Expand().Select().OrderBy().MaxTop(null).Count();
app.MapRestier(routeBuilder => routeBuilder.MapApiRoute<EntityFrameworkApi<MoneyMachineDbContext>>("odata", "odata"));
I try to add a row to the Categories table with Postman:
- First Try
POST https://localhost:44372/odata/Categories
Body 1:
{
"Name": "Guilty Pleasures"
}
I get 500 internal server error: “Object reference not set to an instance of an object.”
Same error with Body 2:
{
"Name": "Guilty Pleasures",
"Expenses": []
}
- Second try
with body
{
"Name": "Guilty Pleasures",
"[email protected]": null or [] or {}
}
I get 400 bad request: “A POST requires an object to be present in the request body.”
However, the post request worked when using an action with Body 1 from First Try:
[HttpPost]
public async Task<IActionResult> AddCategory([FromBody] Category category)
{
context.Categories.Add(category);
await context.SaveChangesAsync();
return CreatedAtAction(nameof(GetCategory), new { id = category.Id }, category);
}
Florin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.