Byron2017
Byron2017

Reputation: 1003

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

}

Upvotes: 0

Views: 389

Answers (2)

Byron2017
Byron2017

Reputation: 1003

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

Upvotes: 0

John Glenn
John Glenn

Reputation: 1629

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

Upvotes: 2

Related Questions