0

I'm trying to factorize the Where clause in following code:

public async Task ExecuteAsync(BatchProcessingModel bpm)
{
    using (_dbFoo = new FooEntities(_fooConnexionString))
    {
        var bprInBdd = await _dbFoo.BatchProcessing
            .Where(x => x.FooAttr1 == bpm.FooAttr1 && x.FooAttr2 == bpm.FooAttr2 && ...)
            .ToListAsync();
        var bprLocal = _dbFoo.BatchProcessing.Local
            .Where(x => x.FooAttr1 == bpm.FooAttr1 && x.FooAttr2 == bpm.FooAttr2 && ...)
            .ToList();

        if (bprLocal.Count == 0 && bprInBdd.Count == 0)
        {
            // add new BatchProcessing in BDD
        }
    }
}

So far, I have tried to add a pseudo equal method to BatchProcessingModel like so:

public bool EqualProcess(BatchProcessing bpr)
{
    return this.FooAttr1 == bpr.FooAttr1 && this.FooAttr2 == bpr.FooAttr2 && ...;
}
var bprInBdd = await _dbFoo.BatchProcessing
    .Where(x => bpm.EqualProcess(x))
    .ToListAsync();
var bprLocal = _dbFoo.BatchProcessing.Local
    .Where(x => bpm.EqualProcess(x))
    .ToList();

But I get an error that says Linq to Entities does not recognize the method. It seems Linq is trying to transform bpm.EqualProcess(x) into a SQL statement but can't do so. Maybe because it doesn't try to read past EqualProcess.

Is there any way I can do a cleaner code? Or should I just stick to the duplication of where clauses?

Oudini
  • 23
  • 1
  • 7
  • So I already found the duplicated thread but didn't understand the answer at the time. I managed to solve my problem with `Expression equalProcess = x => x.FooAttr1 == ...;` and `var bprInBdd = await _dbFoo.BatchProcessing.Where(equalProcess).ToListAsync();` `var bprLocal = _dbFoo.BatchProcessing.AsQueryable().Where(equalProcess).ToList();` – Oudini Sep 10 '21 at 14:10
  • If you wanna stick to linq to entities you should pass an Expression> instead of a Func you are passing in now – Jochem Van Hespen Sep 10 '21 at 14:22
  • wow that's lame i forgot pressing add comment but apparently you already know now :D – Jochem Van Hespen Sep 10 '21 at 14:23

0 Answers0