EF Core: Argument type is not assignable to parameter

.net c# entity-framework entity-framework-core

Question

I have some inheritance chain which start from interface and endsup with actual implmenetation going a couple of steps.

However, this code is 100% correct

IBaseModel model = new ErrorModel();

But when I'm trying something like that:

class MyContext: DbContext{
    public DbSet<ErrorModel> Errors {get; set}
}

and later

DbSet<IBaseModel> set = new MyContext().Errors

this not working (not compiled) and say that Argument Type DbSet<ErrorModel> is not assignable to parameter DbSet<IBaseModel>

What is the problem there and how to resolve it?


UPD1: It's also not working if I'm using base class instead of interface. And code like this

IQueryable<IBaseModel> tests = new MyContext().Errors 

also compiled without any issues.

1
1
7/4/2016 1:35:09 PM

Accepted Answer

This is not working, because DbSet<Item> not inherited from DbSet<BaseItem> and it's logically quite difference things, because DbSet<> is a mutable structure. You could add BaseItem into DbSet<BaseItem> but ofcourse you can't add it to DbSet<Item> so this will not work. With the same reason you can't convert lists or other mutable structures.

However, for immutable structures like IEnumerable or IReadOnlyCollection this conversion will work just fine.

1
7/5/2016 3:30:51 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow