c# - DbContext 对象看不到它的属性 - DbSets

标签 c# entity-framework

<分区>

我的 Web API C# 应用程序具有以代码优先方式构建的 Entity Framework 。 我有一个如下所示的 DbContext 类:

public class AppDbContext : DbContext
{
    public AppDbContext() 
        : base("name=AppDbContext")
    {
    }

    public DbSet<User> Users { get; set; }
    public DbSet<Transaction> Transactions { get; set; }
    public DbSet<MenuItem> MenuItems { get; set; }
    public DbSet<Restaurant> Restaurants { get; set; }

    public static AppDbContext Create()
    {   
        return new AppDbContext();
    }

}

在 Controller 中,我将 DbContext 作为变量调用。

public class AppController : ApiController
{
    private DbContext _context;

    public AppController()
    {
        _context = new AppDbContext();
    }

    protected override void Dispose(bool disposing)
    {
        _context.Dispose();
    }

    [HttpPost]
    public HttpResponseMessage Authorize(User user)
    {
        User currentUser = _context.Users......

Controller 变量 _context 的最后一行无法识别它的属性。 No DbSets in list of properties

如何让它发挥作用?

最佳答案

将字段类型从基本 DbContext 更改为 AppDbContext

private AppDbContext _context;

DbSet 属性在子类中声明,因此它们不能通过基类类型的引用可见。

关于c# - DbContext 对象看不到它的属性 - DbSets,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43925796/

相关文章:

c# - C# 中的简单控制台游戏出现巨大闪烁

entity-framework - 我如何检查 T4 模板 (tt) 文件中的标识列?

c# - 如果该行中的第一列为 null,则 Entity Framework 为该行返回 null

c# - 如何使用 FK 设置集合属性?

entity-framework - 使用通用 dbContext 获取通用存储库(多个 dbContext)

c# - RelativeSource 适用于(嵌套的)子属性,而 ElementName 不适用

c# - 我的多线程创建或覆盖额外/现有线程

c# - 请求被中止 : Could not create SSL/TLS secure channel

c# - 使用 Installutil 安装服务

c# - 使用 Identity 将表添加到 Code-First ASP.NET 应用程序