【问题标题】:how can i solve this error CS0311 ASP.Net Core API我该如何解决这个错误 CS0311 ASP.Net Core API
【发布时间】:2021-04-07 17:35:06
【问题描述】:

Startup.cs 类

namespace API
{
    public class Startup
    {
        public IConfiguration _Config { get; }

        public Startup(IConfiguration config)
        {
            _Config = config;
        }

       

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<DataContext>(options => 
            {
            options.UseSqlite(_Config.GetConnectionString("DefaultConnection"));
            });
           
            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "API", Version = "v1" });
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseSwagger();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "API v1"));
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

DataContext.cs 类

using API.Entities;
using Microsoft.EntityFrameworkCore;

namespace API.Data
{
    public class DataContext : DbContext
    {
        public DataContext( DbContextOptions options) : base(options)
        {
        }

        public DbSet<AppUser> Users { get; set; }
    }
}

Users/sakeeljawfer/Desktop/ASP/DatingApp/API/Startup.cs(34,22):错误 CS0311:类型“API.Data.DataContext”不能用作泛型类型中的类型参数“TContext”或方法'EntityFrameworkServiceCollectionExtensions.AddDbContext(IServiceCollection,Action,ServiceLifetime,ServiceLifetime)'。没有从“API.Data.DataContext”到“Microsoft.EntityFrameworkCore.DbContext”的隐式引用转换。 [/Users/sakeeljawfer/Desktop/ASP/DatingApp/API/API.csproj]

【问题讨论】:

  • 你能展示你的DataContext类吗?
  • using API.Entities; using Microsoft.EntityFrameworkCore; namespace API.Data { public class DataContext : DbContext { public DataContext( DbContextOptions options) : base(options) { } public DbSet&lt;AppUser&gt; Users { get; set; } } }@Sergey

标签: c# asp.net asp.net-mvc asp.net-core


【解决方案1】:

您必须将 DataContext 类修复为:

public class DataContext : DbContext
{ 
public DataContext() 
{
}
        
public DataContext( DbContextOptions<DataContext> options) : base(options)    
{
}          
.....

【讨论】:

    猜你喜欢
    • 2017-05-25
    • 2016-07-21
    • 2016-09-09
    • 2015-02-28
    • 2013-08-16
    • 2020-04-17
    相关资源
    最近更新 更多