Lambda Expression: How to select from two non-related tables with one query - c#-4.0

Would you help me to re-write this query syntax with lambda expressions?
(From Entity.Apple a in db.Context.Apples
From Entity.Bikini b in db.Context.Bikinis
Where a.Id== 10
Where b.Id== 15
Select new {NaturalColor: a.Color, FavoriteColor: b.Color }).FirstOrDefault();
I try to find specific records of two non-related tables, with one connection. In my example, next step may be this:
FindColorDiffrent(Naturalcolor, FavoriteColor){}

db.Context.Apples
.SelectMany(a => db.Context.Bikinis, (a, b) => new {a, b})
.Where(x => x.a.Id == 10)
.Where(x => x.b.Id == 15)
.Select(x => new {NaturalColor: x.a.Color, FavoriteColor: x.b.Color })
.FirstOrDefault();

Related

Having() count of id's on joined table

I am trying to make this query in OrmLite:
select b.* from blog b
join blog_to_blog_category btbc on b.id = btbc.blog_id
join blog_category bc on btbc.blog_category_id = bc.id
where b.url like '%.com' and bc.id in (100, 583)
group by b.id
having count(distinct bc.id ) = 1
I can't figure out how to get the Having() method structured. I can see there is a Sql.CountDistinct() method but I can't figure out how to use it with Having().
I figure I need to do something along the lines of:
var q = db
.From<Blog>()
.LeftJoin<BlogToBlogCategory>()
.Join<BlogToBlogCategory, BlogCategory>()
.Where<BlogCategory>(x => Sql.In(x.Id, 100, 583))
.GroupBy<Blog>(bc => bc.Id)
.Having(x => Sql.CountDistinct("blog_category.id") == "2")
This gives error:
42883: operator does not exist: bigint = text
I can't see how to type it to take a table column name and return a number for comparison.
Is this query possible?
EDIT
I got around it by setting having expression explicitly
q.HavingExpression = $"having count(distinct {q.Table<BlogCategory>()}.{q.Column<BlogCategory>(bc => bc.Id)}) = 2";
I am still curious though if it is possible to do this with fluent api.
I've just added multiple typed table overloads for Having() in the latest v5.11.1 that's now available on MyGet which will allow you to reference a joined table properties in a typed expression, e.g:
var q = db
.From<Blog>()
.LeftJoin<BlogToBlogCategory>()
.Join<BlogToBlogCategory, BlogCategory>()
.Where<BlogCategory>(x => Sql.In(x.Id, 100, 583))
.GroupBy<Blog>(bc => bc.Id)
.Having<BlogCategory>(x => Sql.CountDistinct(x.Id) == 2)

PySpark - How to sort by the value inside the ResultIterable?

I'm building an RDD:
kk = preRatings.filter(lambda a:a.rating>0).map(lambda b:(b.user,(b.product,b.rating)))
How can I sort by the rating value(desc) and get top 10 results with the format(user,(product,rating)?
BTW, I'm referring this scala code and don't know what the author is trying to do inside the case
preRatings
.filter(_.rating > 0)
.map(rating => (rating.user,(rating.product, rating.rating)))
.groupByKey()
.map{ case (uid,recs) =>
UserRecs(uid,recs.toList.sortWith(_._2 >_._2)
.take(10)
.map(x => Recommendation(x._1,x._2)))
}.toDF()
specifically, this line:
recs.toList.sortWith(_._2 >_._2)
What does this mean by comparing with the same _2?

Cassandra connector -- difference between joinWithCassandraTable and leftJoinWithCassandraTable -- Cannot Resolve symbol

I am trying to access data from Cassandra by joining using the datastax cassandra connector. The below code is working for me. I am trying to sum up value columns from RDD and Cassandra after join
tm(a.joinWithCassandraTable("ks","tbl").on(SomeColumns("key","key2","key3","key4","key5","key6","key7","key8","key9","key10","key11","key12","key13","key14","key15","column1","column2","column3","column4","column5")).select("value1").map { case (ip, row) => IP(ip.key, ip.key2, ip.key3,ip.key4,ip.key5,ip.key6,ip.key7,ip.key8,ip.key9,ip.key10,ip.key11,ip.key12,ip.key13,ip.key14,ip.key15,ip.column1,ip.column2,ip.column3,ip.column4,ip.column5,ip.value1 + row.getLong("value1")) }.saveToCassandra("ks", "tbl"))
However, when I try to do a left join, it gives a "Cannot Resolve symbol getLong"
I believe this is due to the fact that left join does not guarantee a value, since it could be null, but I am not able to code this in scala.
tm(a.leftJoinWithCassandraTable("ks","tbl").on(SomeColumns("key","key2","key3","key4","key5","key6","key7","key8","key9","key10","key11","key12","key13","key14","key15","column1","column2","column3","column4","column5")).select("value1").map { case (ip, row) => IP(ip.key, ip.key2, ip.key3,ip.key4,ip.key5,ip.key6,ip.key7,ip.key8,ip.key9,ip.key10,ip.key11,ip.key12,ip.key13,ip.key14,ip.key15,ip.column1,ip.column2,ip.column3,ip.column4,ip.column5,ip.value1 + row.getLong("value1")) }.saveToCassandra("ks", "tbl"))
Any help is appreciated. If there is any information that is needed, let me know and I will try to add
when you don't get data in Cassandra, you should get an Option[Row] instead of Row object.
Instead of .map { case (ip, row) => ...} you can write:
.map { case (ip, row) =>
row match {
case None => ip
case Some(data) => IP(...., ip.value1 + data.getLong("value1"))
}
}
in this case - when you don't have data (None), then you just return IP object itself, and if you have data then you construct new IP object

Table alias lost when using joins with SqlExpressionSelectFilter

I have a situation where records should be excluded depending on a value in a related table. When using joins with SqlExpressionSelectFilter the generated SQL will not use table alias for part of the query. I am running ServiceStack 5.5.
OrmLiteConfig.SqlExpressionSelectFilter = q => {
if (q.ModelDef.ModelType.HasInterface(typeof(IJoinFilter))) {
q.LeftJoin<IJoinFilter, FirstTable>((f, j) => f.FirstTableId == j.Id)
.Where<FirstTable>(j => j.Deleted != true);
}
};
And simply selecting from it with:
db.Select(db.From<SecondTable>().Where<SecondTable>(x => x.Id == 1));
This generates something like:
SELECT SecondTable.Id, SecondTable.FirstTableId, SecondTable.Deleted
FROM SecondTable
LEFT JOIN FirstTable ON (SecondTable.FirstTableId = FirstTable.Id)
WHERE (Id = 1) AND (FirstTable.Deleted <> 1)
Notice the Id in the where clause is not prepended with 'SecondTable'. There are also cases for which the select clause will not include aliases.
Are joins in select filters supported? Is there a recommended way I should be doing this kind of global filter instead?
I've created a quick repro here: https://github.com/TheScobey/OrmliteSelectFilterIssue
The SqlExpressionSelectFilter is applied after the expression is created so wont be able to impact previous expressions, you can try giving the Source From table an alias with:
db.Select(db.From<SecondTable>(db.TableAlias(nameof(SecondTable)))
.Where<SecondTable>(x => x.Id == 1));
An alternative is to force the query to include the table prefix in queries, e.g:
var q = db.From<SecondTable>();
q.PrefixFieldWithTableName = true;
q.Where<SecondTable>(x => x.Id == 1);

how to write SQl Query to LINQ to SQL MVC entity framework

This is my sql Query:
SELECT ParkingPlaceName, NoOfParkingPlaces, COUNT(Place.ParkingAreaID) AS NoOfCarsParked, NoOfParkingPlaces-COUNT(Place.ParkingAreaID)
FROM ParkingArea
LEFT JOIN Place ON ParkingArea.ParkingAreaID = Place.ParkingAreaID
LEFT JOIN Car ON Car.CarID = Place.CarID
GROUP BY ParkingPlaceName, NoOfParkingPlaces, Place.ParkingAreaID
how to write in LINQ to SQL Query
I think you can use DefaultIfEmpty method to perform left outer join between 3 tables with let statements to deal with group results, hence the LINQ version from your SQL query should be similar (or same) like below:
var query = from pa in ParkingArea
from pl in Place.Where(x => pa.ParkingAreaID == x.ParkingAreaID).DefaultIfEmpty()
from ca in Car.Where(x => x.CarID == pl.CarID).DefaultIfEmpty()
group new { pa, pl.ParkingAreaID, ca.CarID } by new { pa.ParkingPlaceName, pa.NoOfParkingPlaces, pl.ParkingAreaID } into grp
let ParkingPlaceName = grp.Select(x => x.ParkingPlaceName)
let NoOfParkingPlaces = grp.Select(x => x.NoOfParkingPlaces)
let NoOfCarsParked = grp.Select(x => x.ParkingAreaID).Count()
select new
{
ParkingPlaceName,
NoOfParkingPlaces,
NoOfCarsParked,
AvailableParkingPlaces = NoOfParkingPlaces - NoOfCarsParked // new alias for holding substraction
};
I decided not to use join ... in ... on ... equals ... directly after first and third from clauses, since it may lead into confusion about which table instance should be handled when creating group elements after performing join.

Resources