带有接口的 .net-core web API 的 CRUD 操作 - saveChanges() 不存在

CRUD operation for .net-core web API with interfaces - saveChanges() doesn't exist

概述

我正在制作一个带有简单 CRUD 操作的 .net-core web API。

我已经创建了 GET 方法并启动它们 运行,但是当我尝试使用 dbContext.Add(myItem) 实现 Create 方法时,我无法使用 dbContext.SaveChanges() 之后。

我当前的作品可在以下位置找到: https://github.com/petermefrandsen/TKD-theory-API

到目前为止

我已经尝试将覆盖方法添加到我的数据库上下文中。 此外,我尝试添加对项目的 entity framework 引用。

因为我确实使用松散耦合的接口,所以当我与教程和其他人的类似问题进行比较时,我不知所措。 (阅读我是 c# 的新手)。

代码

控制器:

[Route("dan/")]
[HttpPost]
public ActionResult<DanTheoryItem> PostDanTheoryItem(DanTheoryItem danTheoryItem)
{
    _context.PostDanTheoryItem(danTheoryItem);
    return new ActionResult<DanTheoryItem>(danTheoryItem);
}

I上下文:

DanTheoryItem PostDanTheoryItem(DanTheoryItem danTheoryItem);

上下文:

public DanTheoryItem PostDanTheoryItem(DanTheoryItem danTheoryItem)
{
    var theoryItem = new DbDanTheoryItems
    {
        Id = danTheoryItem.Id,
        KoreanTheoryItemId = danTheoryItem.KoreanTheoryItemId,
        MainCategory = danTheoryItem.MainCategory,
        SubCategory = danTheoryItem.SubCategory,
        SubToSubCategory = danTheoryItem.SubToSubCategory,
        NameLatin = danTheoryItem.NameLatin,
        NamePhonetic = danTheoryItem.NamePhonetic,
        NameAudio = danTheoryItem.NameAudio
    };
    _dbContext.DanTheoryItems.Add(theoryItem);
    //_dbContext.SaveChanges();
    return danTheoryItem;
}

想要的结果

我想让控制器调用将所需数据写入数据库的上下文方法。

您的界面不包含 SaveChanges 方法。由于您使用的是依赖注入,因此您的控制器只能使用接口中的方法。 如果您在自定义界面中继承自 System.Data.Entity.IDbContext class,该方法将在您的控制器中公开给您。

在您的控制器中实例化您的 DbLokisaurTKDTheoryAppContext class 的实例也会公开 SaveChanges 方法。

很难说清楚,因为您忽略了 post 代码的某些关键部分。然而,我最好的猜测是你 "context" 被提供 IDbContext (你自己创建的),而不是 DbContext,并且你的接口没有定义 SaveChanges 方法.

老实说,干掉IDbContext。接口的要点是定义多个实现之间的契约。这里,只能有一个实现:DbContext,而DbContext甚至不知道这个接口。只需直接注入派生的 DbContext

使用界面并不是魔法棒。你在这里对 Entity Framework 有很强的依赖性,所以接口与否,你是紧密耦合的。不过,这不一定是 bad 的事情。 EF作为你的数据层,这个应用是数据驱动的;无论如何,它都会与数据层紧密耦合。

API 本身就是您的抽象。其他层可能只使用 API,因此不需要进一步的抽象,实际上只是增加了更多的维护问题而没有增加好处。