Search code examples
c#linqentity-framework-6

linq firstordefault criterial inside where


I have 2 tables, TableA and TableB. TableA has a relationship one to many with TableB by the field ElmBId in both tables. I need get a element from TableA but based in a criteria in TableB, so I have sonthing like this:

var criteria = 1;
var ElementA = dbContext.TableA.FirstOrDefault(A => A.ElmBId == A.TableBCollection.FirstOrDefault(B =>B.Criteria == criteria).ElmBId);

This query work well when TableB has elements related from A, but if not, then an exception by null value is threw

To solve this issue I had to split the query into 2 parts like this:

var criteria = 1;
var tmpB = dbContext.TableB.FirstOrDefault(B => B.Criteria == criteria);
var ElementA = null == tmpB ? null : dbContext.TableA.FirstOrDefault(A => A.elmBId == tmpB.elmBId);

However, my question is if is it possible to have the above in a only query?


Solution

  • Have you considered joining the tables?

    var criteria = 1;
    var query = (
        from b in dbContext.TableB
        join a in dbContext.TableA on b.elmBId equals a.elmBId
        where b.Criteria == criteria
        select a)
        .FirstOrDefault();