I am using Blazor with InteractiveServer at the applcation level and Radzen component library.
I would like to create resuable components that fetch their own data for things like dropdowns. For example, I have a Request entity with the following fields:
public class Request
{
public int Id { get; set; }
public int RequesterId { get; set; }
public virtual User Requester { get; set; }
public virtual ICollection<User>? Alternates { get; set; }
}
I am extending the RadzenDropDown component like so:
public class UserDropDown<TValue> : RadzenDropDown<TValue>
{
[Inject] public IDbContextFactory<DataContext> DbFactory { get; set; }
public UserDropDown() : base()
{
TextProperty = nameof(User.FullName);
AllowSelectAll = false;
AllowClear = false;
}
protected override async Task OnInitializedAsync()
{
await base.OnInitializedAsync();
using DataContext dbContext = DbFactory.CreateDbContext();
Data = await dbContext.Users.ToListAsync();
}
protected override async Task OnParametersSetAsync()
{
await base.OnParametersSetAsync();
Chips = Multiple;
}
}
When using the component, I could either bind to request.Requester
or request.RequesterId
. For the alternates, there is an advantage to just binding to the navigation property request.Alternates
and letting the Radzen component handle adding and removing users from the collection. Then I don't have to worry about diffing a list of ids to figure out what operations to perform on the collection. But the parent component using <UserDropDown />
fetches the request in a different dbContext, and EF Core does not see the users in the alternates list as the same objects.
So, I think my options are:
- Override
GetHashCode()
and Equals()
on the Request
class so that EF compares them correctly
- Fetch the list of Users in the parent component and pass them to the UserDropDown
- Work with the ids instead of with the navigation properties
I have tried all three of these approaches and they seem to each have pros and cons. What is the recommended way of accomplishing this?
Thanks!