【问题标题】:The type 'namespace' cannot be used as type parameter 'TContext' in the generic type or method 'DbContextOptions<TContext>'类型“命名空间”不能用作泛型类型或方法“DbContextOptions<TContext>”中的类型参数“TContext”
【发布时间】:2021-06-28 11:56:09
【问题描述】:

您好,我收到了完整的错误消息:The type 'Album.Api.Models.Album' cannot be used as type parameter 'TContext' in the generic type or method 'DbContextOptions&lt;TContext&gt;'. There is no implicit reference conversion from 'Album.Api.Models.Album' to 'Microsoft.EntityFrameworkCore.DbContext'. [Album.Api]

我尝试进行 dotnet ef 迁移,我不得不添加构造函数。我添加了构造函数,但我不知道我做错了什么。 这是我的 Album.cs 模型:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Npgsql.EntityFrameworkCore.PostgreSQL;

namespace Album.Api.Models
{
    
    public class AlbumContext : DbContext
    {
        public AlbumContext(DbContextOptions<Album> options)
            : base(options)
        {
        }
        public DbSet<Album> Albums {get; set;}
        
    }
    
    
    
    
    
    public class Album
    {
        public long Id {get; set;}
        public string Artist {get; set;}
        public string Name {get; set;}
        public string ImageUrl {get; set;}
    }
}

如果有必要,这是我的 startup.cs 配置:

public void ConfigureServices(IServiceCollection services)
        {

            
            services.AddDbContext<AlbumContext>(options =>
            options.UseNpgsql(Configuration.GetConnectionString("DefaultConnection")));
        }

【问题讨论】:

  • 你想要public AlbumContext(DbContextOptions&lt;AlbumContext&gt; options) ... 错误消息对此非常清楚。它告诉你它不能将Album 转换为DbContext,因为Album 不继承自DbContextAlbumContext 确实

标签: c# entity-framework .net-core dbcontext


【解决方案1】:

Album 类是您的实体。 DbContextOptions 类用于您的上下文,在本例中为 AlbumContext。所以你需要改变这一行:

public AlbumContext(DbContextOptions<Album> options)

到这里:

public AlbumContext(DbContextOptions<AlbumContext> options)

对于迁移,您可能还需要实现IDesignTimeDbContextFactory。见https://docs.microsoft.com/en-us/ef/core/cli/dbcontext-creation?tabs=dotnet-core-cli

一些调试技巧...编译器错误会告诉您是哪一行导致了错误,以便您可以缩小范围。如果您使用的是 VisualStudio,您可以单击一个标识符并按 F12 以获取有关它的更多信息。默认情况下,文档 cmets 是折叠的,但对于包含它们的任何包(包括大多数 MS 包),您可以展开它们以获取有关标识符的基本信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多