简体   繁体   中英

Error: 'T' must be a non-abstract type with a public parameterless constructor

I created new .net core 2.1 project. And I created my classes like below. But, I take error in MyRepos.cs .

'MyDbContext' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'TContext' in the generic type or method 'UnitOfWork'

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;       
    }
}

If you add a parameterless constructor to MyDbContext , I think that should fix the issue.

That's what the new() constraint implies.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM