3
public DbSet<Item> Items 
{ 
    get 
    { 
        return dbContext.Item.Where(x => x.Id == id).Select(x=>x)
    }
} 

The above code causes a compilation error:

Cannot implicitly convert type 'System.Linq.IQueryable to ... DbSet.
An explicit conversion exists (are you missing a cast?)

After adding the explicit cast:

public DbSet<Item> Items 
{
     get 
     { 
         return (DbSet<Item>)(dbContext.Item.Where(x => x.Id == id).Select(x => x))
     }
} 

a runtime error happens:

Additional information: Unable to cast object of type 'Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable'1[Item]' to type `'Microsoft.EntityFrameworkCore.DbSet'1[Item]'

Any ideas?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
jan-007
  • 53
  • 6
  • 7
    The result of a query simply *isn't* a `DbSet`. why don't you just change your property return type to `IQueryable`? (And while you're at it, remove the `.Select(x => x)` - it's not doing anything for you.) – Jon Skeet Apr 16 '17 at 11:59
  • Not being able to cast something into type X is usually a sign that the something is *not* of that type X. Why don’t you believe the runtime when it tells you that it cannot do that? – poke Apr 16 '17 at 12:15
  • OK, thanks for your coments. – jan-007 Apr 16 '17 at 12:50
  • @poke The message the "an explicit conversion exist," is confusing at best. It naturally leads to the attempt to do an explicit case. Which then fails with a more clear error message. – Karl Kieninger Oct 16 '19 at 01:25

0 Answers0