1

I am basically trying to perform a left outer join in my LINQ query but I want to return an empty instance of the left-joined object instead of null. My solution below results in an error:

The entity or complex type 'SubObject2' cannot be constructed in a LINQ to Entities query.

 public MyObjectsHolder GetObjectHolder()
     {
         using (MyEntities ctx = new MyEntities()) 
         {
             var query = (from a in ctx.tableA
                          join b in ctx.tableB on b.FKID equals a.PKID into b_a
                          from b in b_a.DefaultIfEmpty()
                          select new MyObjectsHolder()
                          {
                              SubObject1 = a,
                              SubObject2 = b ?? new SubObject2()
                          });

             return query.FirstOrDefault();
         }
     }

1 Answer 1

2

The LINQ to Entities provider is throwing that because it has no way of properly translating that instantiation into a SQL query (which is what LINQ to Entities does). Since your method is only returning one object, I would recommend that you do the following to compensate:

var query = (from a in ctx.tableA
             join b in ctx.tableB on b.FKID equals a.PKID into b_a
             from b in b_a.DefaultIfEmpty()
             select new MyObjectsHolder()
             {
                 SubObject1 = a,
                 SubObject2 = b
             });

var result = query.FirstOrDefault();

if(result != null && result.SubObject2 == null) result.SubObject2 = new SubObject2();

return result;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.