2
votes

My class structure is as follows. I'm trying to include the User field for the Order result. But I don't want to get the Orders property of the User class.

public class Order{
   public int OrderId { get; set; }
   public virtual User User { get; set; }
}

public class User{
   public int UserId {get; set;}
   public string Name {get; set;}
   public string SurName {get; set;}
   public virtual ICollection<Order> Orders { get; set; }
}

I wrote this code.

var orders = context.Set<Order>().Include(t => new { Name = t.User.Name, Surname = t.User.SurName }).ToList();

But I get an error that "The expression 'new <>f__AnonymousType20`2(Name = (t As Order).User.Name, Surname = (t As Order).User.SurName)' is invalid inside an 'Include' operation, since it does not represent a property access: 't => t.MyProperty'. To target navigations declared on derived types, use casting ('t => ((Derived)t).MyProperty') or the 'as' operator ('t => (t as Derived).MyProperty'). Collection navigation access can be filtered by composing Where, OrderBy(Descending), ThenBy(Descending), Skip or Take operations. For more information on including related data, see http://go.microsoft.com/fwlink/?LinkID=746393."

Use .Select() instead of .Include() ?Cid
But wouldn't that slow down my query anyway?ezgigokdemir
This appears to be LINQ to Entities for Entity Framework: if it is please tag correctly. If it isn't tag with the LINQ provider you are using.Richard
@ezgigokdemir .Select() will make the query faster. You're trying to use Include as if it was Select already. LINQ isn't magic, nor a replacement for SQL. A LINQ query is translated to a SQL SELECT query. When you don't use an explicit` Select` you're effectively executing SELECT *, loading all fields in a row even if you only need 1 of them. By using a .Select() to specify a few fields only, you generate a SELECT that only loads those fields.Panagiotis Kanavos