Search code examples
unit-testinglinq-to-sqlmolesdefaultifempty

DefaultIfEmpty Linq to Sql returning null in Moles test


I made a moles in for testing my repository class and it works when I put DefaultIfEmpty(new Drivers()) but when I run the program, I get this error: Unsupported overload used for query operator 'DefaultIfEmpty'.

But when I put it back to DefaultIfEmpty(), it works fine but my*strong text* moles test now returns a null value.. Here is my code:

 var result = from p in this.context.AirPositions
                         join a in this.context.Airplane p.airplane_id equals a.id
                         join s in this.context.Status on p.status_id equals s.id
                         join dp in this.context.DriversPositions on p.id equals dp.position_id into dpJoin
                         from ds in dpJoin.DefaultIfEmpty(new DriversPosition())
                         join d in this.context.Drivers on ds.driver_id equals d.id into dsJoin
                         from drs in dsJoin.DefaultIfEmpty(new Driver())
                         orderby p.timesent descending
                         select new PositionViewModel()
                         { ... };

Solution

  • It seems there is a problem with code that runs with Linq-to-Sql and Linq-to-Object.

    I solved it with the following:

    var result = from p in this.context.AirPositions
                 join a in this.context.Airplane on p.asset_id equals a.id
                 let driver = (from dd in this.context.DriversPositions.Where(u => u.position_id == p.id)
                 join d in this.context.Drivers on dd.driver_id equals d.id
                 select d).FirstOrDefault()
                 orderby p.timesent descending
                 select new PositionViewModel() {...}
    

    Hope this helps other people :)