简体   繁体   中英

Cannot implicity convert type System.Linq.Expression<System.Func<Object, bool>> to bool

actually I have an Expression like this that work very well in the case of Linq to Entity

public static Expression<Func<Tender, bool>> GetPublic()
{
    var now = DateTime.Now.GetEasternStandardDateTime();

    return tender => tender.EndDate > DateTime.Now &&
                     tender.IsClosed == false && 
                     tender.IsCancel == false && 
                     tender.PrivacyLevelId == 1;
}

I can use the expression like this : _repositoryObject.Where(GetPublic()) and I will get results.

But I cannot use the same expression when I have to do Linq to SQL pattern like this

var results = from t in Tenders
              where Tender.GetPublic()
              select t;

I have this error

Cannot implicity convert type System.Linq.Expression> to bool for Linq to SQL

and I don't know why...

Karine

Firstly, I suspect you actually mean you can call it as:

_repositoryObject.Where(GetPublic())

It's important that you call the method to get the expression tree.

Your query expression is being converted into:

var results = Tenders.Where(t => Tender.GetPublic());

... which isn't what you're looking for. Basically, query expressions are translated into method calls using lambda expressions. You don't want that in this case, so you shouldn't use a query expression.

If you want to do other things with a query expression, you can always mix and match, eg

var results = from t in Tenders.Where(Tender.GetPublic())
              where t.SomeOtherProperty
              select t.SomethingElse;

If you change your method to take an IQueryable<Tender> , and return another IQueryable<Tender> where your criteria are added, then it might work.

public static IQueryable<Tender> AddPublicCriteria(this IQueryable<Tender> tenderQuery) {
    // I've omitted your call to DateTime.Now.GetEasternStandardDateTime()
    // since you do not use it.
    return tenderQuery
        .Where(tender => tender.EndDate > DateTime.Now &&
                         tender.IsClosed == false && 
                         tender.IsCancel == false && 
                         tender.PrivacyLevelId == 1
         );
}

var query = Tenders;                       // Original table or data-set
query = query.AddPublicCriteria();         // Add criteria
var results = query.ToList();              // Run query and put the results in a list

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM