phil123456
phil123456

Reputation: 1648

.NET Core - EntityFrameworkCore - Unable to cast object of type 'Query.Internal.EntityQueryable` to type 'DbSet`

I try to implement a search with entity when a search field is provided

but I get a weird casting error I just dont understand

Unable to cast object of type 'Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1[SomeApp.Models.Partner]' to type 'Microsoft.EntityFrameworkCore.DbSet`1[SomeApp.Models.Partner]'.

here is the code of my controller entry point

I tried forcing the cast, but apparently there is something wrong with my code

[HttpPost]
public async Task<ActionResult<PartnersFetch>> GetPartners(PartnersSearch partnersSearch)
{
    DbSet<Partner> data = _context.Partners;
    if (partnersSearch.SearchById != null)
    {
        // the following line causes problems :
        data = (DbSet <Partner>) data.Where( p => p.Id == partnersSearch.SearchById.GetValueOrDefault());
    }
        

thanks for helping me on this

Upvotes: 3

Views: 23206

Answers (2)

phil123456
phil123456

Reputation: 1648

I forgot to use AsQueryable

var data = _context.Partners.AsQueryable();
if (partnersSearch.SearchById != null)
{
    data = data.Where( p => p.Id == partnersSearch.SearchById.GetValueOrDefault());
}

Upvotes: 6

MikeJ82
MikeJ82

Reputation: 332

data.Where(...) will return an IQueryable which you can materialize as follows

List<Partner> myResult = data.Where(...).ToList();

The DbSet<Partner> is only the set on which you can query data. Your goal very likely is to get the partners out of it, right?

Upvotes: 2

Related Questions