how to select specific number of child entities instead of all in entity framework 3.5? - entity-framework

i am wondering how can i select specific number of child objects instead of taking them all with include?
lets say i have object 'Group' and i need to select last ten students that joined the group.
When i use '.Include("Students"), EF includes all students. I was trying to use Take(10), but i am pretty new to EF and programming as well, so i couldn't figure it out.
Any suggestions?
UPDATED:
ok, i have Group object already retrieved from db like this:
Group group = db.Groups.FirstOrDefault(x=>x.GroupId == id)
I know that i can add Include("Students") statement, but that would bring ALL students, and their number could be quite big whether i need only freshest 10 students. Can i do something like this: var groupWithStudents = group.Students.OrderByDescending(//...).Take(10);?
The problem with this is that Take<> no longer appears in intellisense. Is this clear enough? Thanks for responses

I believe Take(10) would be correct.
var Students= (from c in Groups
orderby c.DateAdded descending
select c).Take(10);
My experience with Take though is that it generates some awful sql.
EDIT:
see if this blog post helps, it talks of conditional includes.
http://blogs.msdn.com/b/alexj/archive/2009/10/13/tip-37-how-to-do-a-conditional-include.aspx

Couldn't make Gratzy's suggestion with conditional include work... and found the solution here: http://msdn.microsoft.com/en-us/library/bb896249.aspx
Query would look like this:
group.Students.Attach(group.Students
.CreateSourceQuery()
.OrderByDescending(x=>x.JoinDate)
.Take(10));
This is exactly what i was looking for!
Thanks for all responses anyway!

Related

TYPO3 7.6 Backend module to list values from several tables

I have been struggling for some time now and I can't really find anyone having done the same thing before.
I'm creating a backend module in TYPO3 7.6 which belongs to a shop extension.
The shop extension with the backend module was created with the extension builder. The shop has the following three models:
Product (products which can be ordered through the shop)
Productsorder (link to the customer)
ProductsorderPosition (the ordered product, the ordered amount and size and the link to the Productsorder)
The customers are of a model type from a different extension. These customers are linked to fe_users.
Now what I wanna do in my backend module is getting an overview to all these orders listed with the customer, some information about the fe_user and of course the product. I have created a sql-query, which does exactly that:
SELECT p.productname, p.productpriceperpiece,
pop.amount, pop.size,
h.name, h.address, h.zipcode, h.city, h.email, h.phone,
f.first_name, f.last_name, f.email
FROM `tx_gipdshop_domain_model_productorderposition` AS pop
JOIN `tx_gipdshop_domain_model_product` AS p ON pop.products = p.uid
JOIN `tx_gipdshop_domain_model_productsorder` AS po ON pop.productorder = po.uid
JOIN `tx_gipleasedisturbhotels_domain_model_hotel` AS h ON po.hotel = h.uid
JOIN `fe_users` AS f ON h.feuser = f.uid
If I use this query from the product repository it gives back the right amount of data records but they're of type product and the products are all "empty" (uid = 0 etc).
I've added an additional action for this in the product controller (getOrdersAction) and in the repository containing the query I've added a method findAllOrders.
I'm still rather a beginner in TYPO3 but I can somehow understand why it returns data sets of type Product when the query is called from the ProductRepository. But what I do not know is how I can get all the information from the query above and list it in the backend module.
I've already thought about moving the query to the ProductsorderPositionRepository but I would probably be faced with a similar problem, it would only return the information from the ProductsorderPosition and everything else would be left out.
Can someone point me to the right direction?
Would I need to create another model with separate repository and controller? Isn't there an easier way?
If you need more information, just ask! ;)
First of all, you are doing a joined query with subsets of data mixed from multiple tables. There is nothing against this.
Because of this, there is no "model" which has the mixed datasets.
If you are using the default query thing in a repository, the magic behind the repository assumes that the result of the query statement reflects the defined base model for this repository.
Moving the query function to another repository does not solve the problem.
You have not provided the code snippet you are executing the sql statement, so I assume you have used the query thing in the repository to execute the statement. Something like this:
$result = $query->statement('
SELECT p.productname, p.productpriceperpiece,
pop.amount, pop.size,
h.name, h.address, h.zipcode, h.city, h.email, h.phone,
f.first_name, f.last_name, f.email
FROM `tx_gipdshop_domain_model_productorderposition` AS pop
JOIN `tx_gipdshop_domain_model_product` AS p ON pop.products = p.uid
JOIN `tx_gipdshop_domain_model_productsorder` AS po ON pop.productorder = po.uid
JOIN `tx_gipleasedisturbhotels_domain_model_hotel` AS h ON po.hotel = h.uid
JOIN `fe_users` AS f ON h.feuser = f.uid', NULL);
or have used the query building stuff.
First solution
The first and simpliest solution would be to retrieve the result as plain php array. Before TYPO3 7.0 you could have done this by using this:
$query->getQuerySettings()->setReturnRawQueryResult(TRUE);
With TYPO3 7.0 this deprecated method was removed from the core.
The only way is to define the query and call $query->execute(TRUE); for now.
This should return the data in pure array form.
This is the simpliest one, but as we are in the extbase context this should not be suffering enough.
Second Solution - no, just an idea that I would try next
The second solution means that you have some work to do and is for now only a suggestion, because I have not tried this by myself.
Create a model with the properties and getter/setters for the result columns of your query
Create a corresponding repository
Third solution
Not nice, but if nothing else works, fall back to the old TYPO3 v4 query methods:
$GLOBALS['TYPO3_DB']->exec_SELECTgetRows([...]))
and replace this with the QueryBuilder in/for TYPO3 v8.
This is really not nice.
I hope I could direct you to the right way, even if not giving a full solving solution.

How to query from ListColumn[String] in cassandra using phantom

I am new to cassandra (started learning on my own interest few days back) and looking for help for the below problem.
I have a Cassandra table "User" and a ListColumn "interests extends ListColumn[String]".
Now, I want to fetch all users with an interest, say "playing".
like: select from user where interests.contains("playing")!
I scanned through the ListColumn api but not able to find any. Also, searched in google but no such helpful posts.
Any help guys please... Thanks in Advance :)
So there is contains among operators and here is an example how to use it. It looks like that it should work as any other operator, so just go for database.userTable.select.where(_.interests contains "playing").fetch() - of course, depending on your conventions.
This is possible with a secondary index on a collection column, which only works with a Set column, and not with a List.
Bottom line:
object interests extends SetColumn[String](this) with Index[Set[String]]
And then you can execute the following:
select.where(_.interests contains "test").fetch()
You can also use multiple restrictions if you allow filtering.
select.where(_.interests contains "test")
.and(_.interests contains "test2")
.allowFiltering()
.fetch()
The above will only match if both interests are found in a record.

Linq to Entities query to select latest, distinct records

I'm trying to retrieve records ordered by a DateTime with Linq to entities, but I need them as distinct records as well.
My table design looks like this:
Where blogItemNodeId is an Umbraco CMS node (the blog item node to which a comment can be created)
The requirement is that a list of blog items can be sorted by how many comments they have. So I need to get the latest comments distinct by blogItemNodeId to display those blog items.
My current linq query looks like this:
var distinctComments = (from c in ctx.BlogComments
orderby c.date
group c by c.blogItemNodeId
into uniqueRecords
select uniqueRecords.FirstOrDefault());
The problem with this query is that it finds the first (hence FirstOrDefault()) record with distinct blogItemNodeId where it should find the one which is newest of all comments with the same blogItemNodeId.
Does anyone know how to achieve this? :-)
Thanks a lot in advance.
EDIT
I managed to get it to work by doing this:
var allComments = (from c in ctx.BlogComments
orderby c.date descending
select c).ToList();
var distinctComments = allComments.GroupBy(x => x.blogItemNodeId).Select(y => y.FirstOrDefault());
But then I have to get all the comments before doing the group which is not very elegant nor performant.
Any help is greatly appreciated!
You could combine both the orderBy statement and the GroupBy statement into one single statement like this:
var distinctComments = ctx.BlogComments.OrderBy(c => c.date)
.GroupBy(x => x.blogItemNodeId)
.Select(y => y.FirstOrDefault());
If the performance is bad, you could cache your DataContext in the HttpCache through a Singleton. See this blogpost for an example. This is based on the Umbraco DataContext but can be easily modified for use with another type of context.

MongoID: Group and Count

Supposing I have a model Post, wich contains only the field desc.
The user can use hashtags, like #rails inside any posts...
How can I list and count the hashtags used, for example, in the last 10 days?
I'm do not know much about mongodb, but I see that I could use something called map_reduce.. have no idea why/how.
Thanks in advance.
You are right...this can be solved using mad/reduce function...
try this or this gem if you dont want to think a lot lol
https://github.com/jcoene/mongoid-mapreduce

coldfusion - bind a form to the database

I have a large table which inserts data into the database. The problem is when the user edits the table I have to:
run the query
use lots of lines like value="<cfoutput>getData.firstname#</cfoutput> in the input boxes.
Is there a way to bind the form input boxes to the database via a cfc or cfm file?
Many Thanks,
R
Query objects include the columnList, which is a comma-delimited list of returned columns.
If security and readability aren't an issue, you can always loop over this. However, it basically removes your opportunity to do things like locking certain columns, reduces your ability to do any validation, and means you either just label the form boxes with the column names or you find a way to store labels for each column.
You can then do an insert/update/whatever with them.
I don't recommend this, as it would be nearly impossible to secure, but it might get you where you are going.
If you are using CF 9 you can use the ORM (Object Relation Management) functionality (via CFCs)
as described in this online chapter
https://www.packtpub.com/sites/default/files/0249-chapter-4-ORM-Database-Interaction.pdf
(starting on page 6 of the pdf)
Take a look at <cfgrid>, it will be the easiest if you're editing table and it can fire 1 update per row.
For security against XSS, you should use <input value="#xmlFormat(getData.firstname)#">, minimize # of <cfoutput> tags. XmlFormat() not needed if you use <cfinput>.
If you are looking for an easy way to not have to specify all the column names in the insert query cfinsert will try to map all the form names you submit to the database column names.
http://help.adobe.com/en_US/ColdFusion/9.0/CFMLRef/WSc3ff6d0ea77859461172e0811cbec22c24-7c78.html
This is indeed a very good question. I have no doubt that the answers given so far are helpful. I was faced with the same problem, only my table does not have that many fields though.
Per the docs EntityNew() the syntax shows that you can include the data when instantiating the object:
artistObj = entityNew("Artists",{FirstName="Tom",LastName="Ron"});
instead of having to instantiate and then add the data field by field. In my case all I had to do is:
artistObj = entityNew( "Artists", FORM );
EntitySave( artistObj );
ORMFlush();
NOTE
It does appear from your question that you may be running insert or update queries. When using ORM you do not need to do that. But I may be mistaken.