如何使用 Entity Framework 为两个不同的 models/tables 处理表单数据和提取属性

How do process form data and extract properties for two different models/tables using Entity Framework

我在基于反应的网络游戏上有一个表单,其中包含地牢和英雄数据的表单。

玩家填写后点击提交,发送到我的.NetCore 3.1 Entity Framerwork API.

API 需要将其保存到 2 个不同的模型,以便它可以插入到 2 个不同的数据库 tables。

那些是地下城和英雄。

我有一个应该接受表单数据的控制器,它目前看起来像您在下面看到的那样。

我已经弄清楚如何使用一种模型更新一个数据库table,但是我该如何为两个模型更新呢?

这是我已经开始编写的非工作控制器代码:

[HttpPost]
public async Task<ActionResult<CreateDungeon>> ProcessForm([FromBody]CreateDungeon data)
{
    // Read quest data from form and add to DB via EF
    _context.Quest.Add(data.Quest);
    try
    {
        await _context.SaveChangesAsync();
    }
    catch (DbUpdateException)
    {
        if (QuestExists(data.Quest.Id))
        {
            return Conflict();
        }
        else
        {
            throw;
        }
    }

    // Read heroes data from form and add to DB via EF
    _context.Heroes.Add(data.Heroes);
    try
    {
        await _context.SaveChangesAsync();
    }
    catch (DbUpdateException)
    {
        if (HeroesExists(data.Heroes.Id))
        {
            return Conflict();
        }
        else
        {
            throw;
        }
    }

    return Ok();
}

这是正确的做法吗?

谢谢!

要在ef-core 中存储两个不同的数据库,您需要创建两个不同的dbcontext。

首先,在appsettings.json文件中:

"ConnectionStrings": {
    "DefaultConnection": "Connection string of the database where the quest table is located",
    "NewConnection": "Connection string of the database where the Heroes table is located"  }

那么,你应该有两个dbcontext:

public class FirstdbContext : DbContext
{
    public FirstdbContext (DbContextOptions<FirstdbContext > options) : base(options)
    {
    }
    public DbSet<Quest> Quest { get; set; }

}



public class SeconddbContext : DbContext
{
    public SeconddbContext (DbContextOptions<SeconddbContext > options) : base(options)
    {
    }
    public DbSet<Heroes> Heroes { get; set; }

}

在 startup.cs ConfigureServices 方法中:

 public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews();
        services.AddDbContext<FirstdbContext >(options =>
 options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
        services.AddDbContext<SeconddbContext >(options =>
 options.UseSqlServer(Configuration.GetConnectionString("NewConnection")));
    }

以上设置完成后,controller需要引用这两个dbcontext

[Route("api/[controller]")]
[ApiController]
public class HomeController : ControllerBase
{
    private readonly MydbContext _context1;
    private readonly TestdbContext _context2;

    public HomeController (MydbContext context1, TestdbContext context2)
    {
        _context1 = context1;
        _context2 = context2;
    } 
    [HttpPost]
    public async Task<ActionResult<CreateDungeon>> ProcessForm([FromBody]CreateDungeon data)
    {
        // Read quest data from form and add to DB via EF
        _context1.Quest.Add(data.Quest);
        try
        {
            await _context1.SaveChangesAsync();
        }
        catch (DbUpdateException)
        {
            if (QuestExists(data.Quest.Id))
            {
                return Conflict();
            }
            else
            {
                throw;
            }
        }

        // Read heroes data from form and add to DB via EF
        _context2.Heroes.Add(data.Heroes);
        try
        {
            await _context2.SaveChangesAsync();
        }
        catch (DbUpdateException)
        {
            if (HeroesExists(Heroes.Id))
            {
                return Conflict();
            }
            else
            { 
                throw;
            }
        }

        return Ok();
    } 

}