Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding virtual method with generics and constraints

I'm trying to override the DbContext.Set<TEntity>() method.

It's signature is:

public virtual DbSet<TEntity> Set<TEntity>() where TEntity : class

First I tried this:

public override DbSet<TEntity> Set<TEntity>()
{
    return base.Set<TEntity>();
}

... but I get the error:

The type 'TEntity' must be a reference type in order to use it as parameter 'TEntity' in the generic type or method 'System.Data.Entity.DbContext.Set()'

... so I then tried specifiying it was a reference type:

public override DbSet<TEntity> Set<TEntity>() where TEntity: class
{
    return base.Set<TEntity>();
}

... and I now get:

Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly.

... and if I take it away, I'm back to the first error.

So what does the C# compiler want me to do?

like image 794
Frankie B Avatar asked Sep 13 '14 08:09

Frankie B


2 Answers

Well this is lame... I was using version 6.0.0 of Entity Framework.

In 6.0.0 (after digging through the history of the project on Code Plex, I found out that Set<TEntity>() wasn't virtual back then.

Shame the compiler couldn't say that, rather than sending me round the houses.

Anyway, updating Entity Framework to 6.1.x (where it is virtual), solved the problem;

Update-Package EntityFramework
like image 79
Frankie B Avatar answered Oct 18 '22 18:10

Frankie B


Can you please post an entire class.

Here is how I am using and I can compile without any problem.

public class MyDBContext : DbContext
{
    public override DbSet<TEntity> Set<TEntity>()
    {
        return base.Set<TEntity>();
    }
}

Please make sure that you are using latest Entity Framework (6.X)

like image 1
codebased Avatar answered Oct 18 '22 17:10

codebased