Getting pagination to work with one to many join - servicestack

I'm currently working on a database with several one-to-many and many-to-many relationships and I am struggling getting ormlite to work nicely.
I have a one-to-many relationship like so:
var q2 = Db.From<GardnerRecord>()
.LeftJoin<GardnerRecord, GardnerEBookRecord>((x, y) => x.EanNumber == y.PhysicalEditionEan)
I need to return a collection of ProductDto that has a nested list of GardnerEBookRecord.
Using the SelectMult() technique it doesn't work because the pagination breaks as I am condensing the left joined results to a smaller collection so the page size and offsets are all wrong (This method: How to return nested objects of many-to-many relationship with autoquery)
To get the paging right I need to be able to do something like:
select r.*, count(e) as ebook_count, array_agg(e.*)
from gardner_record r
left join gardner_e_book_record e
on r.ean_number = e.physical_edition_ean
group by r.id
There are no examples of this in the docs and I have been struggling to figure it out. I can't see anything that would function like array_agg in the Sql object of OrmLite.
I have tried variations of:
var q2 = Db.From<GardnerRecord>()
.LeftJoin<GardnerRecord, GardnerEBookRecord>((x, y) => x.EanNumber == y.PhysicalEditionEan)
.GroupBy(x => x.Id).Limit(100)
.Select<GardnerRecord, GardnerEBookRecord>((x, y) => new { x, EbookCount = Sql.Count(y), y }) //how to aggregate y?
var res2 = Db.SelectMulti<GardnerRecord, GardnerEBookRecord>(q2);
and
var q2 = Db.From<GardnerRecord>()
.LeftJoin<GardnerRecord, GardnerEBookRecord>((x, y) => x.EanNumber == y.PhysicalEditionEan)
.GroupBy(x => x.Id).Limit(100)
.Select<GardnerRecord, List<GardnerEBookRecord>>((x, y) => new { x, y });
var res = Db.SqlList<object>(q2);
But I can't work out how to aggregate the GardnerEBookRecord to a list and keep the paging and offset correct.
Is this possible? Any workaround?
edit:
I made project you can run to see issue:
https://github.com/GuerrillaCoder/OneToManyIssue
Database added as a docker you can run docker-compose up. Hopefully this shows what I am trying to do

Npgsql doesn't support reading an unknown array or records column type, e.g array_agg(e.*) which fails with:
Unhandled Exception: System.NotSupportedException: The field 'ebooks' has a type currently unknown to Npgsql (OID 347129).
But it does support reading an array of integers with array_agg(e.id) which you can query instead:
var q = #"select b.*, array_agg(e.id) ids from book b
left join e_book e on e.physical_book_ean = b.ean_number
group by b.id";
var results = db.SqlList<Dictionary<string,object>>(q);
This will return a Dictionary Dynamic Result Set which you'll need to combine into a distinct id collection to query all ebooks referenced, e.g:
//Select All referenced EBooks in a single query
var allIds = new HashSet<int>();
results.Each(x => (x["ids"] as int[])?.Each(id => allIds.Add(id)));
var ebooks = db.SelectByIds<EBook>(allIds);
Then you can create a dictionary mapping of id => Ebook and use it to populate a collection of ebooks entities using the ids for each row:
var ebooksMap = ebooks.ToDictionary(x => x.Id);
results.Each(x => x[nameof(ProductDto.Ebooks)] = (x["ids"] as int[])?
.Where(id => id != 0).Map(id => ebooksMap[id]) );
You can then use ServiceStack AutoMapping Utils to convert each Object Dictionary into your Product DTO:
var dtos = results.Map(x => x.ConvertTo<ProductDto>());

Related

WHERE IN with Azure DocumentDB (CosmosDB) .Net SDK

Having seen this question I'm not sure why the following code for my DocDb instance isn't working:
var userApps = _docs.CreateDocumentQuery(UriFactory.CreateDocumentCollectionUri(Constants.Databases.Applications.ID, Constants.Databases.Applications.Collections.USER_APPS),
new SqlQuerySpec(#"SELECT r.appId FROM ROOT r WHERE r.userId = #userId", (#"#userId", userId).ToSqlParameters()))
.ToList()
.Select(s => (string)s.appId);
var query = _docs.CreateDocumentQuery<Document>(UriFactory.CreateDocumentCollectionUri(Constants.Databases.Applications.ID, Constants.Databases.Applications.Collections.APP_DEFINITIONS),
new SqlQuerySpec(#"SELECT r.id, r.appName FROM ROOT r WHERE r.appId IN (#userApps)", (#"#userApps", userApps.ToArray()).ToSqlParameters()),
new FeedOptions { EnableCrossPartitionQuery = true })
.AsDocumentQuery();
When I execute this, though I know the data should be returning me back a result set, it comes back empty every time.
Troubleshooting so far
Variants of .Select()
Return strings that I string.Join in to a comma-separated list.
Eg:
var userApps = string.Join(#",", _docs.CreateDocumentQuery(UriFactory.CreateDocumentCollectionUri(Constants.Databases.Applications.ID, Constants.Databases.Applications.Collections.USER_APPS),
new SqlQuerySpec(#"SELECT r.appId FROM ROOT r WHERE r.userId = #userId", (#"#userId", userId).ToSqlParameters()))
.ToList()
.Select(s => $#"'{s.appId}'");
Don't encapsulate IN parameter
Removing the () around the parameter spec in the query thinking maybe the SqlParameter spec was doing the array specification?
Eg: #"SELECT r.id, r.appName FROM ROOT r WHERE r.appId IN #userApps")
Ends up throwing "Syntax error, incorrect syntax near '#userApps'."
Validate via Azure Portal queries
Ran the (expected) SQL that this code should be running.
I get back my expected results without issue (ie: I know there is a result set for these queries as-written).
Debugger output for Query 1
AppIds are coming back from query 1.
Unsatisfactory workaround
Change query 2 to not be parameterized. Rather, inject the comma-separated list of IDs from query 1 in to it:
var userApps = string.Join(#",", _docs.CreateDocumentQuery(UriFactory.CreateDocumentCollectionUri(Constants.Databases.Applications.ID, Constants.Databases.Applications.Collections.USER_APPS),
new SqlQuerySpec(#"SELECT r.appId FROM ROOT r WHERE r.userId = #userId", (#"#userId", userId).ToSqlParameter()))
.ToList()
.Select(s => $#"'{s.appId}'"));
var query = _docs.CreateDocumentQuery<Document>(UriFactory.CreateDocumentCollectionUri(Constants.Databases.Applications.ID, Constants.Databases.Applications.Collections.APP_DEFINITIONS),
new SqlQuerySpec($#"SELECT r.id, r.appName FROM ROOT r WHERE r.appId IN ({userApps})"),
new FeedOptions { EnableCrossPartitionQuery = true })
.AsDocumentQuery();
Works perfectly but I'm not going to accept it as an answer to this problem as it goes against a couple decades-worth of SQL best practices and, frankly, shouldn't be a solution.
Here's my ToSqlParameters() extension method in case it's the culprit (this works everywhere else I've used it, though. Maybe something special is needed for arrays?):
public static SqlParameterCollection ToSqlParameters(this (string, object) parmDef) => new SqlParameterCollection(new[] { new SqlParameter(parmDef.Item1, parmDef.Item2) });
Thanks!
If you use a parameterized IN list, then it will be considered as a single value when the parameter is expanded.
For instance, for this query:
SELECT * FROM r WHERE r.item IN (#items) And #items is defined as "['val1', 'val2', 'val3']" will be interpreted as such:
SELECT * FROM r WHERE r.item IN (['val1', 'val2', 'val3'])
which basically means that you're comparing r.item to a single value that is an array of three elements (i.e. equivalent to r.item = ['val1', 'val2', 'val3']).
To compare to multiple items, you need to use a parameter for each value. Something like this: SELECT * FROM r WHERE r.item IN (#val1, #val2, #val3])
A more convenient way to write this query is to use ARRAY_CONTAINS instead and pass the array of items as a single parameter. So the above query will be written like this:
SELECT * FROM r WHERE ARRAY_CONTAINS(#items, r.item)

ServiceStack OrmLite - Is it possible to do a group by and have a reference to a list of the non-grouped fields?

It may be I'm still thinking in the Linq2Sql mode, but I'm having a hard time translating this to OrmLite.
I have a customers table and a loyalty card table.
I want to get a list of customers and for each customer, have a list of express cards.
My strategy is to select customers, join to loyalty cards, group by whole customer table, and then map the cards to a single property on customer as a list.
Things are not named by convention, so I don't think I can take advantage of the implicit joins.
Thanks in advance for any help.
Here is the code I have now that doesn't work:
query = query.Join<Customer, LoyaltyCard>((c, lc) => c.CustomerId == lc.CustomerId)
.GroupBy(x => x).Select((c) => new { c, Cards = ?? What goes here? });
Edit: I thought maybe this method:
var q = db.From<Customer>().Take(1);
q = q.Join<Customer, LoyaltyCard>().Select();
var customer = db.SelectMulti<Customer,LoyaltyCard>(q);
But this is giving me an ArgumentNullException on parameter "key."
It's not clear from the description or your example code what you're after, but you can fix your SelectMulti Query with:
var q = db.From<Customer>()
.Join<Customer, LoyaltyCard>();
var results = db.SelectMulti<Customer,LoyaltyCard>(q);
foreach (var tuple in results)
{
Customer customer = tuple.Item1;
LoyaltyCard custCard = tuple.Item2;
}

complex entityframework query

I have two tables:
NewsRooms ( NrID[int] , NrName [string]);
RawNews( RnID [int], NrID[string]);
realtion is RawNews 1 * NewsRooms
so i use checkboxes for NewsRooms and save the ids as a string in RawNews like this ';1;2;'
now for example i have a list which contains some NrIDs . i want to select every RawNew which it's NrID contains any of the ids inside that list.
here is my code:
var temp = Util.GetAvailibleNewsRooms("ViewRawNews");
List<string> ids = new List<string>();
foreach (var item in temp)
ids.Add(";" + item.NrID.ToString() + ";");
model = db.RawNews.Where(r => r.NrID.Any(ids));
the line model = db.RawNews.Where(r => r.NrID.Any(ids)); is wrong and i don't know how to write this code. please guide me. thanks
ok guys, i found the solution myself so i post it here maybe some other guy need it some day!!
model = model.Where(r => ids.Any(i => r.NrID.Contains(i)));

Entity framework - group by and count clause

I want to write an query with group by and count clause in Entity framework. like employees and managers and display all employees based on manager
any code samples
Thanks
var employeesByManager = db.Employees.
GroupBy(emp => emp.Manager.EmployeeName, emp => emp).
ToList();
var employeeCountsByManager = db.Employees.
Select(emp => new { ManagerName = emp.EmployeeName, EmployeeCount = emp.Employees.Count() }).
Where(a => a.EmployeeCount > 0).
ToList();
You can, of course, get the employees grouped by manager in a similar manner as counts. The GroupBy method is just a simpler way to do this.

Kohana 3 ORM: How to perform query with 2 many to many relationships

I have a products model with 2 many to many relationships defined.
protected $_has_many = array
(
'foodcats' => array('model' => 'foodcat', 'through' => 'products_foodcats'),
'foodgroups' => array('model' => 'foodgroup', 'through' => 'products_foodgroups')
)
I need a query where I find products with a given foodcat id and a given foodgroup name.
I know I can do the following to get all products with a given foodcat id
$foodcat = ORM::factory('foodcat',$foodCatId);
$products = $foodcat->products->find_all();
But how do I query for products in that foodcat that also are in the foodgroup 'Entrees'?
Thanks!
Simply; you don't. What you need is INNER JOIN, like;
ORM::factory('product')
->join('foodcats','INNER')
->on('foodcats.id','=',$foodcats_id)
->join('foodgroups','INNER')
->on('foodgroups.name','=',$foodgroups_name)
->find_all();
in Kohana 3.1 without using DB::expr, will give unknown column error.
ORM::factory('product')
->join('foodcats','INNER')
->on('foodcats.id','=', DB::expr($foodcats_id))
->join('foodgroups','INNER')
->on('foodgroups.name','=', DB::expr($foodgroups_name))
->find_all();

Resources