错误:'T'必须是具有公共无参数构造函数的非抽象类型

问题描述 投票:-1回答:1

我创建了新的.net核心2.1项目。我创建了我的课程,如下所示。但是,我在MyRepos.cs中犯了错误。

'MyDbContext'必须是具有公共无参数构造函数的非抽象类型,以便在泛型类型或方法'UnitOfWork'中将其用作参数'TContext'

UnitOfWork.cs

public class UnitOfWork<TContext> : IUnitOfWork<TContext> where TContext : DbContext, new()
{ }

IUnitOfWork.cs

public interface IUnitOfWork<U> where U : DbContext
{ }

MyRepos.cs

public class MyRepos : UnitOfWork<MyDbContext>, IMyRepos
{ }

IMyRepos.cs

public interface IMyRepos : IUnitOfWork<MyDbContext>
{ }

MyDbContext.cs

public class MyDbContext : DbContext
{
    public MyDbContext(DbContextOptions options) : base(GetOptions())
    { }

    public static DbContextOptions GetOptions()
    {
        return SqlServerDbContextOptionsExtensions.UseSqlServer(new DbContextOptionsBuilder(), "myConnectionString").Options;       
    }
}
c# asp.net-core-2.1
1个回答
2
投票

如果你向MyDbContext添加一个无参数构造函数,我认为应该解决这个问题。

这就是new()约束所暗示的。

© www.soinside.com 2019 - 2024. All rights reserved.