operator '.' cannot be applied to lambda expression - json

I'm trying to create linq lambda expression to return customer whose first or last name starts with specific letters. However i get the error on .select saying that:
operator '.' cannot be applied to lambda expression.
public JsonResult GetCust(string term)
{
var data = context.Customers
.Where((dr => dr.First.StartsWith(term) == true) || (dr => dr.Last.StartsWith(term) == true))
.Select(dr => new { Name=String.Concat(dr.First, dr.Last), Adrs = dr.Street, value = dr.CustID })
.Take(10);
return Json(data, JsonRequestBehavior.AllowGet);
}
Any idea how can I return needed data?

In the following line:
.Where((dr => dr.First.StartsWith(term) == true) || (dr => dr.Last.StartsWith(term) == true))
you are using the ||-Operator on two lambda-expressions.
The Where-Clause should more look like this:
.Where(dr => dr.First.StartsWith(term) || dr.Last.StartsWith(term))

Related

exists query in slick

i have query like bellow
override def isOnList(id: Long, value: String)(implicit ex: ExecutionContext): DBIO[Boolean] = {
tableQuery.filter(e => e.id === id && e.isActive && e.value === value).exists.result
}
But it returns false when the table does not any rows with id === id. I would like to change this. My modification is
override def isOnList(id: Long, value: String)(implicit ex: ExecutionContext): DBIO[Boolean] = {
tableQuery.filter(e => e.id === id && e.isActive).result.flatMap {
case seq if seq.isEmpty => DBIOAction.successful(true)
case seq => DBIOAction.successful(seq.exists(_.value==value))
}
}
I am new with slick, so i would like to know that is it good solution or not (i coud not find any information.)?
Oh i forgot, Id is not unique.
What is wrong with your first option? It seems to be perfectly valid!
def isOnList(id: Long, value: String)(implicit ex: ExecutionContext) : Future[Boolean] =
db.run(User.filter(e => e.id === id && e.isActive && e.value === value).exists.result)
This method should automatically return true or false depending on the filter condition!

Getting type from class

I've been working on a project that stores case classes in a database and can take them back out again, storing them works fine but I am having trouble with getting them back out.
For items like Strings, Ints, Floats, etc, are being stored as they are but other types are converted to a JSON string using json4s like so
private def convertToString(obj: AnyRef, objType: Class[_]): String = {
implicit val formats = Serialization.formats(NoTypeHints)
objType match {
case t if t == classOf[String] => obj.asInstanceOf[String]
case t if t == classOf[Int] => obj.toString
case t if t == classOf[Integer] => obj.toString
case t if t == classOf[Boolean] => if (obj.asInstanceOf[Boolean]) "true" else "false"
case t if t == classOf[Short] => obj.toString
case t if t == classOf[Double] => obj.toString
case t if t == classOf[Long] => obj.toString
case t if t == classOf[Float] => obj.toString
case t if t == classOf[Byte] => obj.toString
case _ => write(obj)(formats)
}
}
This is working fine and store items just like I would expect it to, but the problem is converting the items back from JSON.
Lets say I have the case class Test(testInt: Int, testString: String, testMap: Map[String, _]) and I get the data back as 3,'blablabla','{"Test": "Map"}'
I can put all values into a new instance of the class expect for the map, here is the code I am using
private def restoreTypes(objClass: Class[_], argList: Array[Object]): Array[_ <: Object] = {
var correctTypes = Array.empty[Object]
val fields = objClass.getDeclaredFields
for(i <- 0 until fields.length) {
val giveType = argList(i).getClass
val wantedType = fields(i).getType
if(giveType != wantedType && giveType == classOf[String])
read[/*HERE*/](argList(i).asInstanceOf[String])
else
correctTypes = correctTypes :+ argList(i)
}
correctTypes
}
And this method is called list so
objClass.getConstructors()(0).newInstance(restoreTypes(objClass, args): _*)
I am getting stuck on how to pass the wanted type to the read method

Conditional Anonymous type

I am working on Web API and using Anonymous type to make JSON as output. I am stuck in the following scenario:
If there is no record(VALUE) available then i don't want to show that KEY. Meaning, Key should only appear when and only when there is value.
Below is the JSON object i am creating -
"TU": [
{
"BLOCK": [
[
"00:00",
"00:59"
]
]
}
],
"WE": [],// empty
"TH": [],// empty
"FR": [],// empty
"SA": [] // empty
Here for Tuesday we do have records and hence its showing but later for WE,TH,FR,SA there are not records and hence i don't want to show them so my result will be MO/TU only.
I am using below code:
var result = new
{
CustomerID = custId,
DeviceID = dId,
Kind = kind,
WebList = filter.Select(filt => new
{
URL = filt.FilterName,
TimeBlockFlag = new ChicoHelper().GetFlag(browserlimit, filt.ID, filt.FilterOptionID, KindId),
DAILY = browserlimit.Where(xx => xx.FilterID == filt.ID && xx.OptionTypeID == daily).Select(xx => xx.BlockTimeLimit).SingleOrDefault(),
WEEKLY = browserlimit.Where(xx => xx.FilterID == filt.ID && xx.OptionTypeID == weekly).Select(xx => xx.BlockTimeLimit).SingleOrDefault(),
MONTHLY = browserlimit.Where(xx => xx.FilterID == filt.ID && xx.OptionTypeID == monthly).Select(xx => xx.BlockTimeLimit).SingleOrDefault(),
HASVALUES = browserlimit.Where(xx => xx.FilterID == filt.ID).Count() > 0 ? 1 : 0,
BLOCKTYPE = new ChicoHelper().GetBlockType(browserlimit,filt.ID,filt.FilterOptionID,KindId),
SU = blockedlimit.Where(x => x.OptionID == sunday && x.FilterID == filt.ID).GroupBy(x => new { x.BlockDay })
.Select(x => new
{
BLOCK = x.Select(y =>
new[] { y.BlockStartTime.MakeFormatedTime(), y.BlockEndTime.MakeFormatedTime() }
)
}),
MO = blockedlimit.Where(x => x.OptionID == monday && x.FilterID == filt.ID).GroupBy(x => new { x.BlockDay })
.Select(x => new
{
BLOCK = x.Select(y =>
new[] { y.BlockStartTime.MakeFormatedTime(), y.BlockEndTime.MakeFormatedTime() }
)
}),
TU = blockedlimit.Where(x => x.OptionID == tuesday && x.FilterID == filt.ID).GroupBy(x => new { x.BlockDay })
.Select(x => new
{
BLOCK = x.Select(y =>
new[] { y.BlockStartTime.MakeFormatedTime(), y.BlockEndTime.MakeFormatedTime() }
)
}),
// if i can put some condition like if there is not record for WE then don't show it.
WE = blockedlimit.Where(x => x.OptionID == wednesday && x.FilterID == filt.ID).GroupBy(x => new { x.BlockDay })
.Select(x => new
{
BLOCK = x.Select(y =>
new[] { y.BlockStartTime.MakeFormatedTime(), y.BlockEndTime.MakeFormatedTime() }
)
}),
The main reason for doing this is to reduce the JSON size which will be consumed by Mobile Devices.
Please help me with this.
The properties of an anonymous type are fixed at compile-time - you can't make them conditional. However, some other approaches you might want to think about:
You could investigate whether a property is still included in the JSON representation if its value is null. If it's not, you could add an extension method NullIfEmpty() which returns null if its input is empty.
You could try performing the JSON conversion from the anonymous type in code first, then delete any properties with an empty set of results, then just return that JSON object from the API. (I don't know Web API myself, but there must be a way of saying "Here's a JSON object - ask it for its string representation" rather than using an anonymous type.)
You could ditch the anonymous type entirely, and build up the JSON representation programmatically, setting just the properties you want.
In any approach, I would strongly advise you to extract a common method to come up with the property value based on a day of the week, so you can have:
...
SU = blockedLimit.GetDayBlocks(sunday),
MO = blockedLimit.GetDayBlocks(monday),
TU = blockedLimit.GetDayBlocks(tuesday),
...
There's no reason to have all that code repeated 7 times. In fact, I'd probably refactor that part before doing anything else - it'll make it easier to experiment.

string to int inside linq2sql lambda expression

I have a lambda expression that returns the sum of two fields in a table. The problem is that the field (ExpectedQuantity) is a string, while QtyExpected is an int. I thought I would be able to use int.Parse in my lambda expression, but I get an error saying that SQL cannot translate it.
return new QuantitiesDashboardAggregate()
{
QtyExpected = query.Sum(x => int.Parse(x.ExpectedQuantity)),
QtyReceived = query.Sum(x => int.Parse(x.ReceivedQuantity)),
};
Can someone help?
Here is how I defined the query variable:
IQueryable<Data.POProduct> query = this.Database.POProducts;
// Apply date range
DateRange dateRange = new DateRange(args.DateRangeFilter, args.DateRangeCriteria);
switch (dateRange.DateRangeFilter)
{
case DateRangeFilter.Date:
query = query.Where(po => po.PurchaseOrder.FiscalDate.Date == dateRange.Date);
break;
case DateRangeFilter.FiscalWeek:
query = query.Where(po => (po.PurchaseOrder.FiscalDate.Year == dateRange.Year) &&
(po.PurchaseOrder.FiscalDate.WeekYear == dateRange.Number));
break;
case DateRangeFilter.FiscalPeriod:
query = query.Where(po => (po.PurchaseOrder.FiscalDate.Year == dateRange.Year) &&
(po.PurchaseOrder.FiscalDate.Period == dateRange.Number));
break;
case DateRangeFilter.FiscalYear:
query = query.Where(po => po.PurchaseOrder.FiscalDate.Year == dateRange.Year);
break;
default:
break;
}
Basically Linq to SQL cannot translate your expression, so you should call .ToList() (or .AsEnumerable()) on your query, it will fetch data drom db, and than you can use your expression with int.Parse

Linq - pulling a value from a null query result

I have a linq query that needs to pull a date column out of a row. The expression currently looks like this
myObject.OrderByDescending(s=> s.MyDate).Where(s => s.CRAStatus.Description == "CheckedOut").FirstOrDefault().MyDate)
The problem is that if there are no rows that are "CheckedOut", the query will return a null and attempting to get "MyDate" will throw an exception. We have some verbose solutions, like:
.ForMember(dest => dest.CheckOutDate, opt => opt.MapFrom(src => {
var temp = src.CRAStatusChangeEvents.OrderByDescending(s=> s.MyDate).Where(s => s.CRAStatus.Description == "CheckedOut").FirstOrDefault();
return temp == null ? temp.MyDate : null;
}));
But it would be nice to find something a little more concise. Any Ideas?
Why not
myObject.OrderByDescending(s=> s.MyDate)
.Where(s => s.CRAStatus.Description == "CheckedOut")
.Select(s => s.MyDate as DateTime?)
.FirstOrDefault();
or
myObject.Where(s => s.CRAStatus.Description == "CheckedOut")
.Max(s => s.MyDate as DateTime?);
One option is to set the default if empty to an "empty" instance (think of string.Empty--its a known instance that represents an empty result):
var date = (myObject
.OrderByDescending(s=> s.MyDate)
.Where(s => s.CRAStatus.Description == "CheckedOut")
.DefaultIfEmpty(MyObject.Empty)
.FirstOrDefault()).MyDate;
Here's a snippet that shows how it works:
var strings = new string[]{"one", "two"};
var length =
(strings.Where(s=>s.Length > 5)
.DefaultIfEmpty(string.Empty)
.FirstOrDefault()).Length;
run that and length is 0. Remove the DefaultIfEmpty line and you get a NRE.
var checkedOut = myObject.Where(s => s.CRAStatus.Description == "CheckedOut");
if (checkedOut.Count() > 0) {
var result = checkedOut.Max(s=> s.MyDate).MyDate;
}
How about an extension method?
static class MyObjectEnumerableExtensions
{
public static TMember GetMemberOfFirstOrDefault<TMember>(this IEnumerable<MyObject> items, Func<MyObject, TMember> getMember)
{
MyObject first = items.FirstOrDefault();
if (first != null)
{
return getMember(first);
}
else
{
return default(TMember);
}
}
}
Sample usage:
List<MyObject> objects = new List<MyObject>();
objects.Add(new MyObject { MyDate = DateTime.MinValue });
var filteredObjects = from s in objects where s.MyDate > DateTime.MinValue select s;
DateTime date = filteredObjects.GetMemberOfFirstOrDefault(s => s.MyDate);
Console.WriteLine(date);