Q:

How to check item matches predicate

Got a generic repository, works fine. The repository got 2 constructors:
    private IDbSet<T> mDbSet;
    private Expression<Func<T, bool>> mPredicate;
    ...  

    public Repository()
    {
        mDbSet = mDb.Set<T>();
        mPredicate = null;
    }

    public Repository(Expression<Func<T, bool>> predicate)
    {
        mDbSet = mDb.Set<T>();
        mPredicate = predicate;
    }

The second to supply a "standard" filter on items in the repository. The filter applies on output as well as on input. So the Add function needs the check whether the element matches the predicate. How to do that. The following does not compile:
public virtual void Add(ref T item)
{
    if (mPredicate != null)
    {
        List<T> chkList = new List<T>() { item };

        if (chkList.FirstOrDefault(mPredicate) == null)
        {
            throw new AppExcpetion("Add non-matching element.");
        }
    }

    mDbSet.Add(item);
}

The FirstOrDefault works fine for non-gerenic lists. But perhaps I don't need a list to check the item matches the predicate. Thanks in advance for any help!

A:

First of all, you have to compile the expression to use it for checking. It would be probably best to store the compiled function instead of re-compiling it on Add:
private readonly Expression<Func<T, bool>> mPredicate;
private readonly Func<T, bool> predicate;

public Repository(Expression<Func<T, bool>> predicate)
{
    mDbSet = mDb.Set<T>();
    mPredicate = predicate;
    this.predicate = mPredicate.Compile();
}

Also ref is not necessary (or needed) on the parameter:
public virtual void Add(T item)
{
    if (predicate != null && !predicate(item))
    {        
        throw new AppExcpetion("Add non-matching element.");
    }
    mDbSet.Add(item);
}

