Search code examples
asp.net-mvc-3entity-framework-4lambdarepository

Cannot convert lambda expression to type 'string' because it is not a delegate type


In my controller i am trying to use include with EF4 to select related entities, but the lambda expression is throwing the following error,

i have the related entity defined in the Entity class like

public class CustomerSite
{
    public int CustomerSiteId { get; set; }
    public int CustomerId { get; set; }
    public virtual Customer Customer { get; set; }
}

Then in my controller i have

 var sites = context.CustomerSites.Include(c => c.Customer);

 public ViewResult List()
 {
    var sites = context.CustomerSites.Include(c => c.Customer);
    return View(sites.ToList());
 }

Can anyone kindly point me in the right direction on what i'm doing wrong here?


Solution

  • The Include method expects a string, not a lambda:

    public ViewResult List()
    {
        var sites = context.CustomerSites.Include("Customer");
        return View(sites.ToList());
    }
    

    Of course you could write a custom extension method which would work with lambda expressions and make your code independant of some magic strings and refactor friendlier.

    But whatever you do PLEASE OH PLEASE don't pass EF autogenerated objects to your views. USE VIEW MODELS.