Accessing DbContext Directly without WebAPI in ASP.NET Core 3.0

Asked 2 years ago, Updated 2 years ago, 152 views

I am currently studying how to build a web server using ASP.NET Core 3.0 and Blazor.
 After searching for online tutorials, we found a way to access databases such as SQL Server using WebAPI using the following URL:

var url="http://localhost:9999/api/item";
var response = new HttpClient().GetStringAsync(url);
variable=JsonConvert.Deserialize<Item>(response);

Instead of accessing the database through WebAPI like this, is there a way to access the database directly with the C# written on the web page, for example?

Var context=GetContext();// Access DbContext in a nice way
Get the object you want directly from the variables=context.Items;//DbContext object

I apologize for the ambiguous question, but I appreciate your cooperation.

asp.net entity-framework asp.net-core .net-core

2022-09-30 16:40

2 Answers

I've never used Blazor, but
With EintitiFrameworkCore, scuffling would be the easiest.

Scaffold-DbContext"server=(local); user id=sa;Password=;database=DatabaseName""Microsoft.EntityFrameworkCore.SqlServer"-OutputDirModels-f

Reference URL:
https://docs.microsoft.com/ja-jp/ef/core/managing-schemas/scaffolding?tabs=dotnet-core-cli


2022-09-30 16:40

I'm learning how to build a web server using Blazor

I don't know if it's a web server in Blazor (I'm afraid there's something wrong with it), but let's leave it alone...

In the case of the Blazor WebAssembly hosting model, all of the images in the following article appear to be completed on the client side, but it works in a browser, so if you want to communicate with the client/server via HTTP.

ASP.NET Core Blazor Hosting Model
https://docs.microsoft.com/ja-jp/aspnet/core/blazor/hosting-models?view=aspnetcore-3.1

Therefore, the client side C# code to write in Blazor is

Access varcontext=GetContext();//DbContext in a nice way
Get the object you want directly from the items=context.Items;//DbContext object

"As far as I know, ""accessing a good feeling"" by writing like this is impossible."

It may be a different story if you even think about implementing a system that allows you to write your own code and rap around it to communicate with HTTP, but you don't think about it that much, do you?

If you don't want to write code using HttpClient like the one I wrote in the question, there is a way to DI JSRuntime on the Razor page and submit a request using JavaScript in ajax.See the article below for more information.

Call JavaScript function from .NET method in ASP.NET Core Blazor https://docs.microsoft.com/ja-jp/aspnet/core/blazor/call-javascript-from-dotnet?view=aspnetcore-3.1

"However, in that case, ""access DbContext in a good way"" or ""get the object you want directly from the DbContext object"" is still done on the server side of the destination."


2022-09-30 16:40

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.