简体   繁体   English

如何在 Blazor 和 Web API 和一个 ZEFE90A8E604A7C840E888D03A 中使用 Entity Framework Core

[英]How to use Entity Framework Core in Blazor and Web API with one package

I want to build an app which provides web side (Blazor) and app side (Android, iOs, etc which use Web API communication). I want to build an app which provides web side (Blazor) and app side (Android, iOs, etc which use Web API communication). And I want to use EF Core to store my data.我想使用 EF Core 来存储我的数据。

The flow with Blazor and Web API is similar. Blazor 和 Web API 的流程类似。 So I want to use it with one package.所以我想将它与一个 package 一起使用。 Is there any way to Implement it?有没有办法实现它?

The data tier sample, use DI数据层示例,使用 DI

public class UserService : IUserService
{
    private SqlContext db;
    private IDbContextFactory<SqlContext> dbContextFactory;

    public UserService(SqlContext sqlContext, IDbContextFactory<SqlContext> dbContextFactory)
    {
        this.db = sqlContext;
        this.dbContextFactory = dbContextFactory;
    }

    public async Task Add(UserDTO userDTO, UserType Type)
    {
        var u = await db.Users.Where(u => u.Id == userDTO.Id).AsNoTracking().FirstOrDefaultAsync();

        if (u is not null)
        {
            throw new("same ID");
        }

        userDTO.Type = Type;
        var entity = userDTO.MapTo<UserEntity>();
        entity.Type = Type;

        await db.AddAsync(entity);
        await db.SaveChangesAsync();
    }

    public async Task UpdatePassword(string userId, string password)
    {
        var user = await db.Users
                           .SingleAsync(u => u.Id == userId);

        if (password != "")
        {
            user.Password = password.ToSHA512();
        }

        await db.SaveChangesAsync();
    }
}

It's working fine in Web API, but not in Blazor.它在 Web API 中运行良好,但在 Blazor 中运行良好。

Blazor sample Blazor样品

@inject IUserService userService

<SpaceItem><Button Icon="@IconType.Outline.Redo" OnClick="()=>ResetPwd(context.Id)">resetPass</Button></SpaceItem>

    public async Task ResetPwd(string id)
    {
      var pwd = id.Substring(id.Length - 6);
      await userService.UpdatePassword(id, pwd);
    }

There is a problem, when I open the Blazor page, and use API to change password, then use Blazor reset password, the password which is in the response from the database is the last password.有一个问题,当我打开Blazor页面,用API修改密码,然后用Blazor重置密码,数据库响应中的密码是最后一个密码。

https://learn.microsoft.com/en-us/aspnet/core/blazor/blazor-server-ef-core?view=aspnetcore-6.0 https://learn.microsoft.com/en-us/aspnet/core/blazor/blazor-server-ef-core?view=aspnetcore-6.0

And I see dbcontextFactory, when I exec it, I need create every time.我看到 dbcontextFactory,当我执行它时,我每次都需要创建。 I need add one code in every func.我需要在每个函数中添加一个代码。

Is there any good way to get it?有什么好的方法可以获取吗?

First of all you shouldn't call service methods from blazor app.首先,您不应该从 blazor 应用程序调用服务方法。 Blazor should communicate with service and DB through APIs. Blazor 应该通过 API 与服务和数据库通信。 (You can use 'Refit' for maintaining API calls from blazor) (您可以使用“改装”来维护来自 blazor 的 API 调用)

Maybe this is giving issue because you don't have SqlContext and DbContetFactory in blazor like in the API but this service expecting them as injection.也许这是给问题,因为您在 blazor 中没有 SqlContext 和 DbContetFactory ,就像在 API 中一样,但该服务期望它们作为注入。

Firstly your UserService should look something like this using "unit of work" Db contexts - see this MS article for why - https://learn.microsoft.com/en-us/ef/core/dbcontext-configuration/#using-a-dbcontext-factory-eg-for-blazor首先,使用“工作单元”Db 上下文,您的UserService应该看起来像这样 - 请参阅这篇 MS 文章了解原因 - https://learn.microsoft.com/en-us/ef/core/dbcontext-configuration/#using-a -dbcontext-factory-eg-for-blazor

public class UserService : IUserService
{
    private IDbContextFactory<SqlContext> dbContextFactory;

    public UserService(IDbContextFactory<SqlContext> dbContextFactory)
    {
        this.dbContextFactory = dbContextFactory;
    }

    public async Task Add(UserDTO userDTO, UserType Type)
    {
        using db = this.dbContextFactory..CreateDbContext();
        //....
    }

    public async Task UpdatePassword(string userId, string password)
    {
        using db = this.dbContextFactory..CreateDbContext();
        //....
    }
}

You second issue is almost certainly a concurrency issue.您的第二个问题几乎可以肯定是并发问题。 It looks like you've alrady got the information in Blazor when you do the update through the API When do you actually get the user information in Blazor from the database?当您通过 API 进行更新时,您似乎已经获得了 Blazor 中的信息。 Without more information it's hard to be specific.没有更多信息,很难具体说明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Entity Framework Core 添加到 .Net Core Web Api - IRelationalTypeMappingSource 问题 - Entity Framework Core adding to .Net Core Web Api - IRelationalTypeMappingSource problem ASP.NET 核心 Web API 使用实体框架核心 - ASP.NET Core Web API using Entity Framework Core 如何识别一对一关系中的依赖实体 Entity Framework Core? - How to identify a dependent entity in one to one relationship Entity Framework Core? 如何在 Entity Framework Core 中使用 ValueGeneratedOnUpdateSometimes - How to use ValueGeneratedOnUpdateSometimes in Entity Framework Core 如何在实体框架和 EF Core 中使用 .Include() - How to use .Include() in Entity Framework and EF Core 如何在 Entity Framework Core 中使用抽象 class? - How to use abstract class in Entity Framework Core? 如何将LinqPad与Entity Framework Core一起使用? - How to use LinqPad with Entity Framework Core? .NET Web API(非核心)-在Entity Framework控制器中创建修补程序操作 - .NET Web API (not Core) - Creating a Patch operation in an Entity Framework controller 如何从没有实体框架的.NET Core 2.1 Web API中检索类中的连接字符串 - How to retrieve connection string in class from .NET Core 2.1 Web API w/o Entity Framework ASP.NET 核心 Web API - 如何在实体框架结果中获取所有员工用户详细信息和角色 - ASP.NET Core Web API - How get all employees user details and roles in Entity Framework result
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM