Hoodlum
Hoodlum

Reputation: 1503

Generic Repository implementation fails with IEntity constraint

I'm trying to implement a generic repository and it fails because there is no implicit conversion from the DBML object to the generic entity. I don't know how to make the DBML object inherit from IEntity, or if that is even the solution.

Below are the interfaces and the repository signatures I'm using.

public interface IEntity
{
    int ID { get; } 
}

public interface IRepository<T> : IDisposable
{
    ....
}

public class Repository<T> : IRepository<T> where T : class, IEntity
{
    ....
}

This is the Model class. It fails with the error (below) at line 9 where an instance of the repository class is instantiated in the constuctor. This only started happening after I added the IEntity constraint to the Repository class.

public class MyModel
{
    DataContext DC;
    Repository<MyType> MyRep;

    public MyModel()
    {
        DC = new DataContext("ConnStr");
        MyRep = new Repository<MyType>(DC);

    }
}

Here is the error : The type cannot be used as type parameter 'T' in the generic type or method. There is no implicit reference conversion from 'MyType' to 'IEntity'

Thanks in advance for your help.

Upvotes: 0

Views: 1306

Answers (2)

Hoodlum
Hoodlum

Reputation: 1503

D.R.'s answer solved my problem in the short term, but ultimately I implemented partial classes which extend the DBML objects. This approach solved a couple of issues. First, the DBML file doesn't have to be edited every time there are Database changes. Second, this gives me the ability to add other extension properties and methods to the DBML objects when needed.

Upvotes: 0

D.R.
D.R.

Reputation: 21194

It looks likeMyType is not implementing the IEntity interface.

Open your DBML file with an editor and add the following attribute:

EntityBase="IEntity"

to the Database element.

Edit: don't know if that is possible using the UI editor.

Upvotes: 1

Related Questions