Is it possible to have Include work based on function parameter as used in code below. By going throug MSDN documentation for Include, looks like it's not possible.
public static Response<Person> GetById(int id, bool includeAddress = false
, bool includeFiles = false
, bool includeTags = false)
{
var output = new Response<Person>();
using (var dbContext = new SmartDataContext())
{
dbContext.Configuration.ProxyCreationEnabled = false;
output.Entity = dbContext.EntityMasters.OfType<Person>()
.Include(p => includeFiles == true ? p.FileMasters : null)
.Include(p => includeAddress == true ? p.Addresses : null)
.Include(p => includeTags == true ? p.Tags : null)
.FirstOrDefault(e => e.EntityId == id);
}
return output;
}
Is there any trick to handle it directly or I have to build expression instead. I am not sure even how would I build an expression for this rather checking in dbContext. I am thinking if I can build expression before entering dbContext scope.
What I am looking for is to have all the conditions resolved before jumping into USING statement. In example below I creating an expression and using it inside USING
public static Response<IEnumerable<ConfigurationType>> GetByAttributeType(int attributeType)
{
Response<IEnumerable<ConfigurationType>> output = new Response<IEnumerable<ConfigurationType>>();
System.Linq.Expressions.Expression<System.Func<ConfigurationType, bool>> expressions=null;
switch (attributeType)
{
case 1:
expressions = a => a.IsItemAttribute == true;
break;
case 2:
expressions = a => a.IsReadPointAttribute == true;
break;
default:
expressions = a => a.IsPersonAttribute == true;
break;
}
using (var context = new SmartDataContext())
{
context.Configuration.ProxyCreationEnabled = false;
output.Entity = context.ConfigurationTypes.Where(expressions).ToList();
}
return output;
}
Similarly what I am expecting is something like this. This sounds weird, just trying to overthink may be if there is a way to resolve p somehow.
IQueryable<Person> query = includeFiles?Include(p=>p.Files):null; //p is undefined
query.Append(includeTags?Include(p=>p.Tags):null);
I am not sure if it's possible or not. If not, please help me understand the reason.
expression treeas well?EntityMastersin your case). The pieces of your query can be defined elsewhere, or built using expression trees, but you still start with your context because it is the query provider.Includeand more to do with building queries outside of the scope of an entity context.using, there is no object to operate on.