Reputation: 376
I'm using a Blazor
server side app with Entity Framework
.
I have a parent entity Booking
with a child collection of Tours
. I have a page where I add tours to Booking's Tours
collection.
public class Booking
{
IEnumerable<Tours> Tours { get; set; }
}
I have a main parent booking component, which is just a shell for the booking sub-components, like Tours. I pass the child collection to the child component like so on the booking page:
<Tours Tours="Booking.Tours" />
@code {
protected override async Task OnInitializedAsync()
{
Booking = await BookingService.GetBooking(reference);
}
}
However I find that, when I add a Tour, the page does not update with the newly added Tour unless I make a call to fetch the Booking with its children again.
private async Task addTour(TourState state)
{
var newBookingTour = new BookingTour();
var newTour = await BookingTourService.CreateBookingTour(newBookingTour);
// UI ONLY UPDATES WHEN I DO THIS
Booking = await BookingService.GetBooking();
}
Here is the generic method
I use to save entities to the DB
:
public async Task<TEntity> Upsert(TEntity item)
{
var entity = this.Context.Update(item);
await this.SaveChangesAsync();
return entity.Entity;
}
Should I really be making a call to the DB
again? Surely Entity Framework
should pick up the newly added entity and feed it through to the UI
? I feel I'm missing something here!
Any help appreciated as I'm new to both EF
and Blazor
.
Upvotes: 3
Views: 284
Reputation: 979
Should I really be making a call to the DB again?
No, you should not.
Surely Entity Framework should pick up the newly added entity
Yes it does
and feed it through to the UI?
No it wont, you have to
You just have to update your model, you dont have to fetch it from the database as you already have a reference of the new item.
Assuming your service returns the entity:
private async Task addTour(TourState state)
{
var newBookingTour = new BookingTour();
var newTour = await BookingTourService.CreateBookingTour(newBookingTour);
Booking = ExistingBookig.Tours.Add(newTour);
}
Upvotes: 3