Incorrect number of type parameters in reference class MyClass<F,T> Generic entity framework

I've got the following generic abstract class:

public abstract class MyClass<F, T>
    where TCurrencyFrom : Book
    where TCurrencyTo : Book
{
    public int Id { get; set; }
    public virtual F First{ get; set; }
    public virtual T Second { get; set; }
}

And I got 3 classes which implement this class like:

public class Implementation1 : MyClass<BookType1, BookType2>
{
}

public class Implementation2 : MyClass<BookType2, BookType1>
{
}

Now I got an "EntityTypeConfiguration" for those which looks like:

public class MyClassConfiguration<TMyClass> : EntityTypeConfiguration<TMyClass> where TMyClass: MyClass
{
    public MyClassConfiguration()
    {
        ...
    }
}

And try to use those like:

public class Implementation1Map : MyClassConfiguration<Implementation1> 
{
    public Implementation1Map ()
    {
        ...
    }
}

But then I get the following error:

Incorrect number of type parameters in reference class MyClass

How can I solve this problem and make sure I have a generic approach on the EntityTypeConfigurations?

Jon Skeet
people
quotationmark

Unfortunately this is tricky with .NET generics.

If MyClassConfiguration doesn't actually care about the type arguments, you might want to create a non-generic interface:

public interface IMyClass
{
    // Any members of MyClass<,> which don't rely on the type arguments,
    // e.g. the Id property
}

Then make MyClass<,> implement IMyClass:

// Type parameters renamed to make the type constraints sensible...
public abstract class MyClass<TCurrencyFrom, TCurrencyTo> : IMyClass
    where TCurrencyFrom : Book
    where TCurrencyTo : Book

And change the type constraint for MyClassConfiguration:

public class MyClassConfiguration<TMyClass> : EntityTypeConfiguration<TMyClass>
    where TMyClass: IMyClass

(Obviously you'll want to give IMyClass a more useful name...)

Alternatively, just make MyClassConfiguration generic in three type parameters:

public class MyClassConfiguration<TMyClass, TCurrencyFrom, TCurrencyTo>
    : EntityTypeConfiguration<TMyClass>
    where TMyClass: MyClass<TCurrencyFrom, TCurrencyTo>
    where TCurrencyFrom : Book
    where TCurrencyTo : Book

public class Implementation1Map
    : MyClassConfiguration<Implementation1, BookType1, BookType2> 

public class Implementation2Map
    : MyClassConfiguration<Implementation2, BookType2, BookType1>

It's ugly, but it'll work.

people

See more on this question at Stackoverflow