0

This code builds without problems but fails when executed:

var query =
    _db.STEWARDSHIP
        .OrderByDescending(r => r.VisitDate)
        .Where(r => SiteId == null || r.SiteAssoc.Id == iSiteId)
        .Where(r => r.MarkedForDeletion == false)
        .Select(r => new SearchResults(r.Id, 
                                       r.SiteAssoc.Name, 
                                       r.VisitDate, 
                                       r.VisitTypeValAssoc.Description));

The error message is:

Only parameterless constructors and initializers are supported in LINQ to Entities.

What am I doing wrong here? I must pass info to the constructor to build the SearchResults objects. Is there a way to do this or do I have to make this a 2-step thing where I get the results and then iterate over the results to create the new objects?

UPDATE:

Changing the select to this fixes the issue:

 .Select(r => new SearchResults(){Id = r.Id, 
                                 Name = r.SiteAssoc.Name, 
                                 VisitDate = r.VisitDate, 
                                 VisitType = r.VisitTypeValAssoc.Description});

2 Answers 2

1

Try this

 .OrderByDescending(r => r.VisitDate)
        .Where(r => SiteId == null || r.SiteAssoc.Id == iSiteId)
        .Where(r => r.MarkedForDeletion == false)
        .Select(r => new SearchResults()
                                       {
                                       ID = Ir.Id, 
                                       Name = r.SiteAssoc.Name, 
                                       VisitDate = r.VisitDate, 
                                       Description = r.VisitTypeValAssoc.Description
                                       });
Sign up to request clarification or add additional context in comments.

2 Comments

Haris, that did not work, I get that Id, Name, etc does not exist in current context.
You should replace ID, Name etc with actual property name of your SeachResults class
1

Entities can be created outside of queries and inserted into the data store using a DataContext. You can then retrieve them using queries. However, you can't create entities as part of a query.

See this post Explicit construction of entity type '###' in query is not allowed.

LINQ doesn't allow the explicit construction of objects within the select statements.

1 Comment

Thanks for the link. While review the answers, I saw this: c => new AttachmentCulture { Culture = c }; and when I translate into my example, it works. See the note I added to the orignal post.

Your Answer

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