How to access Entity Framework DbContext entities in Server-Side Blazor Components

blazor blazor-server-side entity-framework-core


I'm new to .NET Core and Blazor, with mostly WebForms and MVC experience.

All the Blazor documentation and tutorials I've found use a separate API project and access data through HttpClient and Json serialization/deserialization. I see why this would be necessary for client-side Blazor using WebAssembly, but for Server-Side Blazor using SignalR what's the best way to access the database directly from the components' .razor files using an Entity Framework DbContext?

For example, in an MVC controller you can just do something like:

private ApplicationDbContext context = new ApplicationDbContext();

and then query the data by doing something like:

var things = context.Things.Where(t => t.ThingAttributes == something);

Is there an approach that is this clean and efficient when working with components in server-side Blazor?

Sorry for the broad nature of this question, feel free to point me to blogs, docs, or tutorials I should have already read. Thanks!

1/18/2020 10:27:18 PM

Accepted Answer

What you call a controller should be turned into a service class, that retrieves data from the database, and pass it to the calling methods. You should add this service to the DI container in the Startup class. To use this service in your components you should inject it like this:

@inject DataService myDataService

I think that the Blazor templates come with sample how to define such a service and use it in your components.

Here's a link to a sample by the Blazor team how to create a service and how to use it in your components. The service doesn't use Entity Framework, but this is something really minor I'm sure you'll cope with.

1/19/2020 7:03:05 AM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow