Reputation: 656
I have a class Dog
implementing an interface IAnimal
and an IDbSet<Dog> DogSet
.
I have the following prototype : MyMethod(IDbSet<IAnimal> AnimalSet)
When trying to do MyMethod(DogSet);
I have an error at compilation saying it's not possible to explicitly cast IDbSet<Dog>
to IDbSet<IAnimal>
If I try to cast it using MyMethod((IDbSet<IAnimal>)DogSet)
, I have an error at runtime because it fails to cast.
Why can't I cast it since Dog
implement IAnimal
?
Code :
public interface IAnimal{
public String Libelle { get; }
}
public partial class Dog : IAnimal{
public String Libelle {
get {
return "Hello World";
}
}
}
// Can't convert from 'System.Data.Entity.IDbset<Models.Dog>' to 'System.Data.Entity.IDbSet<Interfaces.IAnimal>'
public abstract MyClass : MyAbstractClass{
public MyClass(IModel dbContext) : base(dbContext, dbContext.DOG_IDBSET) { }
}
public abstract class MyAbstractClass{
public MyAbstractClass(Imodel dbContext, IDbSet<IAnimal>){ }
}
Edited code :
// Can't convert from 'System.Data.Entity.IDbset<Models.Dog>' to 'System.Data.Entity.IDbSet<T>'
public abstract MyClass<T> : MyAbstractClass<T> where T : Dog, IAnimal
{
public MyClass(IModel dbContext) : base(dbContext, dbContext.DOG_IDBSET) { }
}
public abstract class MyAbstractClass<T> where T : Dog, IAnimal
{
public MyAbstractClass(Imodel dbContext, IDbSet<T>){ }
}
Upvotes: 2
Views: 197
Reputation: 2619
By setting generic constraints to require a class implementing interface IAnimal you should be able to do this:
public void MyMethod<T>(DbSet<T> animals) where T : class, IAnimal
{
...
}
...and call as:
MyMethod(DogSet);
Upvotes: 5