I'm trying to build something like conditional queries to get only needed data from the underlying database.
Currently I have the following query (which works fine)
var eventData = dbContext.Event.Select(t => new { Address = true ? new AnonymousEventGetAddress { AddressLine1 = t.Address.AddressLine1, CityName = t.Address.AddressCityName } : new AnonymousEventGetAddress(), }); If I change it to
var includeAddress = true; // this will normally be passed as param var eventData = dbContext.Event.Select(t => new { Address = includeAddress ? new AnonymousEventGetAddress { AddressLine1 = t.Address.AddressLine1, CityName = t.Address.AddressCityName } : new AnonymousEventGetAddress(), }); I get the following error:
The type 'AnonymousEventGetAddress' appears in two structurally incompatible initializations within a single LINQ to Entities query. A type can be initialized in two places in the same query, but only if the same properties are set in both places and those properties are set in the same order.
What am I doing wrong here (as of with the true it's working) and how can this be fixed?
I know that changing the else-part to
new AnonymousEventGetAddress { AddressLine1 = null, CityName = null } will work. But if I change the order of the properties then, this will also fail.
The class used is defined the following:
public class AnonymousEventGetAddress : BaseAnonymousObject<AnonymousEventGetAddress> { public string AddressLine1 { get; set; } public string CityName { get; set; } } whereas BaseAnonymousObject<AnonymousEventGetAddress> is defined:
public abstract class BaseAnonymousObject<TAnonymous> where TAnonymous : BaseAnonymousObject<TAnonymous> { // this is used in case I have to return a list instead of a single anonymous object public static Expression<Func<IEnumerable<TAnonymous>>> Empty => () => new TAnonymous[]{}.AsEnumerable(); }
IQueryablesoExpressionofFuncso these will be compiled to LINQ, they aren't executed...LINQKitto enable the usage ofExpression<>which work pretty fine when passingtrue.Selectexpressions, so in one you are doing it ifincludeAddressor choose the other if otherwise. Don't try and compound it into the expression it will get treated as an expression...include...this would end up in 8 different queries for each combination of them... So I'm still wondering what's different between passingincludeAdress(fails) andtrue(working).