简体   繁体   中英

C# EF 6 - implementing a generic DBContext constructor

I am trying to create a ContextFactory, for an ASP.NET framework 4.8 application but I have this error message:
" CS0314: The type 'TContext' cannot be used as type parameter 'TContext' in the generic type or method 'IContextFactory'. There is no boxing conversion or type parameter conversion from 'TContext' to 'System.Data.Entity.DbContext'. "

Maybe someone know how to solve this problem?

My Interfase Class:

public interface IContextFactory<TContext> where TContext : DbContext
{
    TContext CreateDefault();
}

Interfase implementation Class:

public class ContextFactory<TContext> : IContextFactory<TContext>
where TContext :  new()
{
    public TContext CreateDefault()
    {
        TContext tContext = new TContext();
        return tContext;
    }
}

My Context Class:

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

    public DbSet<Role> Roles { get; set; }

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

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Role>()
            .HasMany(e => e.Users)
            .WithMany(e => e.Roles)
            .Map(m => m.ToTable("UsersInRoles").MapLeftKey(new[] { "Rolename", "ApplicationName" }).MapRightKey("LoginName"));
    }

}

Your class definition must restate the generic type restriction from the interface where TContext: DbContext or have a more restrictive one that fulfills the interface generic type restriction.

You are receiving the error because your class currently only restricts the generic type to being something that can be instantiated, not to a DbContext.

public class ContextFactory<TContext> : IContextFactory<TContext>
where TContext : DbContext

I solved this problem with this changes:

My Interfase Class:

public interface IContextFactory<TContext> 
{
    TContext CreateDefault();
}

Interfase implementation Class:

public class ContextFactory<TContext> : IContextFactory<TContext>
where TContext :  new()
{
    public TContext CreateDefault()
    {
        TContext tContext = new TContext();
        return tContext;
    }
}

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