Josh Bula
Josh Bula

Reputation: 413

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

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!

Upvotes: 2

Views: 5803

Answers (1)

enet
enet

Reputation: 45636

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.

Upvotes: 5

Related Questions