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."
.Select()
instead of.Include()
? – Cid.Select()
will make the query faster. You're trying to useInclude
as if it wasSelect
already. LINQ isn't magic, nor a replacement for SQL. A LINQ query is translated to a SQLSELECT
query. When you don't use an explicit` Select` you're effectively executingSELECT *
, 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 aSELECT
that only loads those fields. – Panagiotis Kanavos