I have the problem to use function inside the where clause in linq query as seen in the code below.
Function which return IEnumerable object:
private IEnumerable filterparameter(string filter)
{
EmailAflAwmMessageDM obj = new EmailAflAwmMessageDM();
if (filter == "attachments")
{
return obj.attachments;
}
else if (filter == "flagged")
{
return obj.flagged;
}
else
{
return obj.seen;
}
}
Function which returns IQuerable, which will be used in web api function:
private IQueryable SearchFilterCondition(string filter,string value)
{
var emailmessage = from a in db.EmailAflAwmMessage
where (filterparameter(filter) == value)
orderby a.msg_date descending
select new
{
a.subject,
a.msg_date,
};
return emailmessage;
}
update: this error
{"Message":"An error has occurred.",
"ExceptionMessage":"The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.",
"ExceptionType":"System.InvalidOperationException",
"StackTrace":null,
"InnerException": {
"Message":"An error has occurred.",
"ExceptionMessage":"LINQ to Entities does not recognize the method 'System.Collections.IEnumerable filterparameter(System.String)' method, and this method cannot be translated into a store expression.",
"ExceptionType":"System.NotSupportedException",
"StackTrace":"
Please help me to resolve this problem or guide me with an alternate.
As @Domysee Mentioned you cannot call any c# function within a Linq query. Only EntitiFunctions That's why expressions have been built for. To be used inside linq queries
public Expression<Func<EmailAflAwmMessage, bool>> GetSelectXpr(string filter, string value)
{
if (filter == "attachments")
return e => e.attachments == value;
else if (filter == "flagged")
return e => e.flagged == value;
else
return e => e.seen == value;
}
Usage.
var selectXpr = GetGetSelectXpr(filter,value);
var emailmessage = db.EmailAflAwmMessage.Where(selectXpr).OrderByDescending(a=>a.msg_date).Select(a=>
new {
a.subject,
a.msg_date
})
Unfortunately it isn't possible to use methods inside a Where of an IQueryable, because Linq to SQL cannot know how to translate your method into SQL.
You have to inline your method into the Where to make it work.
Something like that:
private IQueryable SearchFilterCondition(string filter,string value)
{
var filterParam = filterparameter(filter); //evaluate filterparameter outside of the query
var emailmessage = from a in db.EmailAflAwmMessage
where (filterParam == value)
orderby a.msg_date descending
select new
{
a.subject,
a.msg_date,
};
return emailmessage;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With