OneSmartGuy
OneSmartGuy

Reputation: 2939

Stumped on Entity Framework & Lambda Expressions

I know currently the compiler is not liking this statement. Getting Error

Cannot convert lambda expression to delegate type 'System.Func<MyData.Models.SomeModels,bool>' because some of the return types in the block are not implicitly convertible to the delegate return type

My Statement I'm passing to my Repository Class

var qry = repositoryClass.Find(c => c.Categories.Where(d => d.CategoryParentID == typeID));

Repository Class Find Method

        public IEnumerable<SomeModels> Find(Func<SomeModels, bool> exp)
    {
        return (from col in _db.SomeModels where exp select col);
    }

Upvotes: 0

Views: 4511

Answers (2)

OneSmartGuy
OneSmartGuy

Reputation: 2939

I just added a method in my Repository Class

    public IEnumerable<Models> GetByCategory(int categoryID)
    {
        var qry = _db.ModelCategories.Where(p => p.CategoryID == categoryID).First();
        qry.Models.Load();

        return qry.Models;
    }

I'm guessing because it needs to be loaded this is the best way to go.

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1062820

To work with EF you need an Expression<...>, applied (as a predicate) with Where:

public IEnumerable<SomeModels> Find(Expression<Func<SomeModels, bool>> exp)
{
    return _db.SomeModels.Where(exp);
}

You'd then call that as:

var qry = repositoryClass.Find(c => c.CategoryParentID == typeID);

The lambda is then translated into an Expression<...>.

If your setup is more complex, please clarify.

Upvotes: 4

Related Questions