0

I am building a web API that is suppose to populate data from a linked child table using a where clause. I have attempted using include() with where() as per eager loading but without success.

public IQueryable<Market> getAllActive()
    {
        return db.Markets.Where(c => c.IsActive == true).Include(d => d.TravelCentres.Where(e => e.IsActive == true));

}

On researching, there are recommendations that I use explicit loading but it keeps error about the need to cast the data type. I am lost of ideas at the moment and will appreciate any help. Here is my code:

private TravelCentresDbContext db = new TravelCentresDbContext();    
public IQueryable<Market> getAllActive()
        {
            //return db.Markets.Where(c => c.IsActive == true).Include(d => d.TravelCentres);
            var result = db.Markets
                .Where(c => c.IsActive == true)
                .Select(p => new
                {
                    Market = p.MarketId,
                    TravelCentres = p.TravelCentres.Where(x => x.IsActive == true)
                });
            return (IQueryable<Market>)result;
        }

I get this exception message Unable to cast object of type 'System.Data.Entity.Infrastructure.DbQuery1[<>f__AnonymousType42[System.String,System.Collections.Generic.IEnumerable1[TravelCentres.Models.TravelCentre]]]' to type 'System.Linq.IQueryable1[TravelCentres.Models.Market]'.

Blockquote

1 Answer 1

1

result is not an IQuerytable<Market>, it's an IQueryable of an anonymous type with properties Market and TravelCenters. So (IQueryable<Market>)result is an invalid cast. It would be advisable to create a model with Market and TravelCenters properties and then return that.

public class MyModel
{
    public int MarketId { get; set; }
    public IEnumerable<TravelCentre> TravelCentres { get; set; }
}

.

var result = db.Markets
            .Where(c => c.IsActive == true)
            .Select(p => new MyModel()
            {
                Market = p.MarketId,
                TravelCentres = p.TravelCentres.Where(x => x.IsActive == true)
            });

return (IQueryable<MyModel>)result;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.