I am trying to get the following method to work:
private static IQueryable<TObject> ApplyOrderBy<TObject, TKey>(IQueryable<TObject> query, OrderByDirection orderByDirection,
Expression<Func<TObject, TKey>> sortExpression, ref bool first)
{
if (orderByDirection == OrderByDirection.None || sortExpression == null) return;
if (orderByDirection != OrderByDirection.Ascending && orderByDirection != OrderByDirection.Descending)
throw new Exception(string.Format("Should never get here! Unknown OrderByDirection enum - '{0}'.", orderByDirection));
if (first)
{
first = false;
query = orderByDirection == OrderByDirection.Ascending
? query.OrderBy(sortExpression)
: query.OrderByDescending(sortExpression);
}
else
{
query = orderByDirection == OrderByDirection.Ascending
? ((IOrderedQueryable<TObject>)query).ThenBy(sortExpression)
: ((IOrderedQueryable<TObject>)query).ThenByDescending(sortExpression);
}
return query;
}
This method works great if you call it like this:
ApplyOrderByToGet(ref query, OrderByDirection.Ascending, x => x.StartDateTime, ref first);
The sort expression then has a strongly typed DateTime as the type and LINQ to SQL is happy. However, if you want to pass an array of these expressions with varying types, you ultimately need a list with "object" as the type. Problem is that LINQ to SQL does not figure out that the type is not object, but instead is DateTime. This works with a regular list using LINQ to objects.
Seeing as it’s possible to navigate the expression tree and find out what the type is, would it be possible to cast/convert the expression before calling ApplyOrderBy?
Cast or convert from:
Expression<Func<T, object>>
to:
Expression<Func<T, DateTime>>
Related
I have a nice Linq challenge. I would like to filter some data on a Date using a FilterFunction. It should work like this:
ApplyDateFilterEx(query,null, DateTime.Today, s => s.CreatedDate);
Should filter the query so that all 'shipments' until today are returned. The query object is of IQueryable and the whole query should be evaluated by EF5 and therefore should convert to SQL.
This is what I have so far (DOES NOT COMPILE):
private static IQueryable<Shipment> ApplyDateFilterEx(IQueryable<Shipment> query, DateTime? minDate, DateTime? maxDate, Expression<Func<Shipment, DateTime?>> dateMember)
{
if (minDate != null)
{
//convert func to expression so EF understands
Expression<Func<Shipment, bool>> where = x => minDate <= dateMember(x);
query = query.Where(where);
}
if (maxDate != null)
{
Expression<Func<Shipment, bool>> where = x => dateMember(x) <= maxDate;
query = query.Where(where);
}
return query;
}
You can see I want to convert the expression s=>DateTime? to s=> Bool to be evaluated. How can I get this to work?
Thank you for reading.
Martijn
UDPATE:
I ended up with this (thanks to rdvanbuuren)
var predicate = Expression.Lambda<Func<Shipment, bool>>(
Expression.GreaterThanOrEqual(
selector.Body,
Expression.Constant(dateFilter.MinDate, typeof (DateTime?))
), selector.Parameters);
Have a look at
How to implement method with expression parameter c#
I think that's exactly what you need, but with an Expression.GreaterThanOrEqual or Expression.LessThanOrEqual. Good luck!
The following statement works fine if the source is not null:
Filters.Selection
.Select(o => new GetInputItem() { ItemID = o.ItemId })
It bombs if "Filters.Selection" is null (obviously). Is there any possible way to write my own extension method which returns null if the source is null or else execute the "Select" func, if the source is not null.
Say, something like the following:
var s = Filters.Selection
.MyOwnSelect(o => new GetInputItem() { ItemID = o.ItemId })
"s" would be null if "Filters.Selection" is null, or else, "s" would contain the evaluated "func" using LINQ Select.
This is only to learn more about LINQ extensions/customizations.
thanks.
You could do this:
public static IEnumerable<U> SelectOrNull<T,U>(this IEnumerable<T> seq, Func<T,U> map)
{
if (seq == null)
return Enumerable.Empty<U>(); // Or return null, though this will play nicely with other operations
return seq.Select(map);
}
Yes have a look at the Enumerable and Queryable classes in the framework, they implement the standard query operators.
You would need to implement a similar class with the same Select extension methods matching the same signatures, then if the source is null exit early, you should return an empty sequence.
Assuming you're talking about LINQ to Objects, absolutely:
public static class NullSafeLinq
{
public static IEnumerable<TResult> NullSafeSelect<TSource, TResult>
(this IEnumerable<TSource> source, Func<TSource, TResult> selector)
{
// We don't intend to be safe against null projections...
if (selector == null)
{
throw new ArgumentNullException("selector");
}
return source == null ? null : source.Select(selector);
}
}
You may also want to read my Edulinq blog post series to learn more about how LINQ to Objects works.
I am getting the following error when I ultimately try to run the query
Unknown LINQ expression of type 'IsFalse'
this is the code
private static IQueryable<T> QueryMethod<T>(
IQueryable<T> query,
QueryableRequestMessage.WhereClause.Rule rule,
Type type,
string methodName,
Expression property,
Expression value,
string op,
ParameterExpression parameter
) where T : class
{
var methodInfo = type.GetMethod(methodName, new[] { type });
var call = Expression.Call(property, methodInfo, value);
var expression = rule.Op.Equals(op)
? Expression.Lambda<Func<T, bool>>(call, parameter)
: Expression.Lambda<Func<T, bool>>(Expression.IsFalse(call), parameter);
query = query.Where(expression);
return query;
}
The important variables have the following values
query: an IQueryable that I am building up
type: String
methodName: "EndsWith"
rule.Op: "ne" //Not Ends With
op: "ew"
value: "somestring"
Basically, if op and rule.Op are equal, it just runs the methodName (EndsWith) and filters accordingly. However, If they are different, I want to negate the result.
It seems that you are not doing anything wrong; your LINQ provider simply does not know how to deal with the expression tree instance that Expression.IsFalse returns so it complains.
You can try to manually construct the "is false" expression tree yourself, which should work:
Expression.Lambda<Func<T, bool>>(
Expression.Equal(call, Expression.Constant(false)),
parameter)
I am trying to write a really generic way to load EF entities in batches, using the Contains method to generate a SQL IN statement. I've got it working if I pass the entire expression in, but when I try to build the expression dynamically, I am getting a "The LINQ expression node type 'Invoke' is not supported in LINQ to Entities." So I know this means that EF thinks I'm calling an arbitrary method and it can't translate it into SQL, but I can't figure out how to get it to understand the underlying expression.
So If I do something like this (just showing the relevant snippets):
Function declaration:
public static List<T> Load<T>(IQueryable<T> entityQuery, int[] entityIds, Func<T, int> entityKey, int batchSize = 500, Func<T, bool> postFilter = null) where T : EntityObject
{
var retList = new List<T>();
// Append a where clause to the query passed in, that will use a Contains expression, which generates a SQL IN statement. So our SQL looks something like
// WHERE [ItemTypeId] IN (1921,1920,1922)
// See http://rogeralsing.com/2009/05/21/entity-framework-4-where-entity-id-in-array/ for details
Func<int[], Expression<Func<T, bool>>> containsExpression = (entityArray => (expr => entityArray.Contains(entityKey(expr))));
// Build a new query with the current batch of IDs to retrieve and add it to the list we are returning
newQuery = entityQuery.Where<T>(containsExpression(entityIds));
retList.AddRange(newQuery.ToList());
return retList;
}
Call function:
var entities = BatchEntity.Load<ItemType>(from eItemType in dal.Context.InstanceContainer.ItemTypes
select eItemType
, itemTypeData
, (ek => ek.ItemTypeId)
);
I get "The LINQ expression node type 'Invoke' is not supported in LINQ to Entities."
But if I change it to be this:
Function declaration:
public static List<T> Load<T>(IQueryable<T> entityQuery, int[] entityIds, Func<int[], Expression<Func<T, bool>>> containsExpression, int batchSize = 500, Func<T, bool> postFilter = null) where T : EntityObject
{
var retList = new List<T>();
// Build a new query with the current batch of IDs to retrieve and add it to the list we are returning
newQuery = entityQuery.Where<T>(containsExpression(entityIds));
retList.AddRange(newQuery.ToList());
return retList;
}
Call function:
var entities = BatchEntity.Load<ItemType>(from eItemType in dal.Context.InstanceContainer.ItemTypes
select eItemType
, itemTypeData
, (entityArray => (ek => entityArray.Contains(ek.ItemTypeId)))
);
It works fine. Is there any way I can make EF understand the more generic version?
The problem, as you describe, is that the entityKey function in the first example is opaque since it is of type Func rather than Expression. However, you can get the behavior you want by implementing a Compose() method to combine two expressions. I posted the code to implement compose in this question: use Expression<Func<T,X>> in Linq contains extension.
With Compose() implemented, your function can be implemented as below:
public static List<T> Load<T>(this IQueryable<T> entityQuery,
int[] entityIds,
// note that this is an expression now
Expression<Func<T, int>> entityKey,
int batchSize = 500,
Expression<Func<T, bool>> postFilter = null)
where T : EntityObject
{
Expression<Func<int, bool>> containsExpression = id => entityIds.Contains(id);
Expression<Func<T, bool>> whereInEntityIdsExpression = containsExpression.Compose(entityKey);
IQueryable<T> filteredById = entityQuery.Where(whereInEntityIdsExpression);
// if your post filter is compilable to SQL, you might as well do the filtering
// in the database
if (postFilter != null) { filteredById = filteredById.Where(postFilter); }
// finally, pull into memory
return filteredById.ToList();
}
I have IQueryable object and I need to take the data inside the IQueryable to put it into Textboxs controls. Is this possible?
I try something like:
public void setdata (IQueryable mydata)
{
textbox1.text = mydata.????
}
Update:
I'm doing this:
public IQueryable getData(String tableName, Hashtable myparams)
{
decimal id = 0;
if (myparams.ContainsKey("id") == true)
id = (decimal)myparams["id"];
Type myType= Type.GetType("ORM_Linq." + tableName + ", ORM_Linq");
return this.GetTable(tableName , "select * from Articu where id_tipo_p = '" + id + "'");
}
public IQueryable<T> GetTable<T>(System.Linq.Expressions.Expression<Func<T, bool>> predicate) where T : class
{
return _datacontext.GetTable<T>().Where(predicate);
}
This returns a {System.Data.Linq.SqlClient.SqlProvider+OneTimeEnumerable1[ORM_Linq.Articu]}`
I don't see any method like you tell me. I see Cast<>, Expression, ToString...
EDIT: Updated based on additional info from your other posts...
Your getData method is returning IQueryable instead of a strongly typed result, which is why you end up casting it. Try changing it to:
public IQueryable<ORM_Linq.Articu> getData(...)
Are you trying to query for "Articu" from different tables?
With the above change in place, your code can be rewritten as follows:
ORM_Linq.Articu result = mydata.SingleOrDefault();
if (result != null)
{
TextBoxCode.Text = result.id.ToString();
TextBoxName.Text = result.descrip;
}
If you have a single result use SingleOrDefault which will return a default value if no results are returned:
var result = mydata.SingleOrDefault();
if (result != null)
{
textbox1.text = result.ProductName; // use the column name
}
else
{
// do something
}
If you have multiple results then loop over them:
foreach (var item in mydata)
{
string name = item.ProductName;
int id = item.ProductId;
// etc..
}
First, you should be using a strongly-typed version of IQueryable. Say that your objects are of type MyObject and that MyObject has a property called Name of type string. Then, first change the parameter mydata to be of type IQueryable<MyObject>:
public void setdata (IQueryable<MyObject> mydata)
Then we can write a body like so to actually get some data out of. Let's say that we just want the first result from the query:
public void setdata (IQueryable<MyObject> mydata) {
MyObject first = mydata.FirstOrDefault();
if(first != null) {
textbox1.Text = first.Name;
}
}
Or, if you want to concatenate all the names:
public void setdata(IQueryable<MyObject> mydata) {
string text = String.Join(", ", mydata.Select(x => x.Name).ToArray());
textbo1.Text = text;
}
Well, as the name suggests, an object implementing IQueryable is... Queryable! You'll need to write a linq query to get at the internal details of your IQueryable object. In your linq query you'll be able to pull out its data and assign bits of it where ever you'd like - like your text box.
Here's a great starting place for learning Linq.
I think you find the same mental struggle when coming from FoxPro and from DataSet. Really nice, powerful string-based capabilities(sql for query, access to tables and columns name) in these worlds are not available, but replaced with a compiled, strongly-typed set of capabilities.
This is very nice if you are statically defining the UI for search and results display against a data source known at compile time. Not so nice if you are trying to build a system which attaches to existing data sources known only at runtime and defined by configuration data.
If you expect only one value just call FirstOrDefault() method.
public void setdata (IQueryable mydata)
{
textbox1.text = mydata.FirstOrDefault().PropertyName;
}