How to include related Entities using dynamic queries - entity-framework

I am taking the values from a search form in my application to build a dynamic query:
string queryString = #"SELECT VALUE USERS FROM ProjectDBEntities.Users AS Users
WHERE ";
There are two tables in the database, Users and Photo, table Photo has a column UserId that links to the Users table. A one to many relationship exists between Users and Photo.
After some iteration through the form values and adding System.Data.Objects.ObjectParameter values, I end up with following query:
SELECT VALUE USERS FROM ProjectDBEntities.Users AS Users
WHERE Users.CountryId = 2
Then I have this code:
System.Data.Objects.ObjectQuery<Users> usersQuery =
new System.Data.Objects.ObjectQuery<Users>(queryString, _db);
The usersQuery object does not contain the Image data for each Users. In my View I can iterate through the Users.Image but the Image count is always zero. Do I have to include or attach the Image data somewhere? How?

Just add an .Include() for the image property:
System.Data.Objects.ObjectQuery<Users> usersQuery =
new System.Data.Objects.ObjectQuery<Users>(queryString, _db).Include("Image");

Related

Odata results displaying user id values under certain columns instead of usernames when data imported into excel from devops?

I imported certain Workitems data from my Devops project into excel using Odata queries.
In that data under certain columns for eg: AssignedToUserSK its showing the user id values like this 06ea0e70-432d-4315-8ffd-87706966a7b6
Instead of this i need the username to be displayed instead of user id.
How to solve this?
If you want to see usernames in the Odate query instead of user id, you need add the columns AssignedTo.UserName, CreatedBy.UserName and ChangedBy.UserName. Then you can see the user name.
Result:

Issue failing to get multiple results in CK query where the same record may be returned more than once

I've got a table in CloudKit (UserCourse) which holds a reference to a user, a reference to a course and a variety of summary data for that User+Course combo (e.g., date starte, status, etc). A user could choose to take the same course multiple times.
In one view of my app, I show the count of courses a user has taken - this query works fine and shows the total count, including duplicate versions of a user+course combination.
I then have a subsequent view, where I want to list out all of the courses the logged in user has taken, with course details. My issue is that I'm only able to get a single copy of the Course that has been duplicated.
First I have a query that gets all records from the UserCourses table for that user. From the results, I get the references to all of the courses and pass that as an input to a subsequent query that attempts to get all the courses from CK so that I can display the view to the user of all the courses they have taken.
The issue is that I'm unable to get two copies of the same course (say one in progress and one completed, as an example). I've tried querying by recordName, but I understand that isn't possible. However, when I try to convert from recordName to Record ID (below) - I get different record IDs for the same record name and my query only returns one instance of the Course, not two.
recordIDs.append(CKRecord.ID(recordName: recordName))
and the relevant code below. Open to suggestions on how to address it. I'm guessing I'm going about it the wrong way and should be designing my queries differently!
func getCoursesByReference(for references: [CKRecord.Reference],
_ completion: #escaping ([Course]?,Error?) -> Void) {
var recordIDs: [CKRecord.ID] = []
for each in references { //loop through the references being passed in
// and because you can't query by recordName in cloudkit, then convert to record ID
var recordName = each.recordID.recordName
recordIDs.append(CKRecord.ID(recordName: recordName))
}
//my predicate now has two different record IDs for the same recordName and as such my results set is 1 item instead of two
var predicate = NSPredicate(format: "recordID IN %#", recordIDs)
let query = CKQuery(recordType: "Course", predicate: predicate)
....remainder of code

How to store markers (with id) and populate map for each user using mongodb?

I'm a complete noob so bear with me please -
Currently users can add markers and my plan is to use the ondraw event to get the marker lat/lng and store that in mongodb, however i don't know how to get the individual markerID - ._leaflet_id returns same id for every marker.
But if i generate id for the marker using something like Date.now() how can i fetch that id from db if a user clicks on a marker? Each marker needs to be unique since each one will have a different redirect for onclick().
Thank you
I had a similar issue sometime back. What I did was create a table with [unique key id] and another column as markerJson,
var marker = new L.Marker([0, 0]);
// Get the GeoJSON object
var geojson = marker.toGeoJSON();
which has the following
{
"type":"Feature",
**"properties":{},**
"geometry":{
"type":"Point",
"coordinates":[0,0]
}
}
Save the above json in markerjson Column created above.
You can see in the json above the properties feature "properties":{}, does the logic
from db fetch and append the [unique key id] to properties "properties":{} e.g
"properties":{unique-key_id:28}, now user can access the unique id from properties.
But in the case above on creating an event, the create event has properties{} feature, just append _leaflet_id to properties with the generated Id with Date.now().

How can a free tagging field be created in a Microsoft access form?

Setup
Access 2007
This is a simplified scenario. It is nearly identical to my actual use case just easier to explain. I have a many to many relationship between movies and genres the table structure is below.
Table: movies
id autonumber
name text
Table: genres
id autonumber
name text
Table: movie_genres
movie_id number
genre_id number
I would like a form that allows me to list all genre's for a given movie. But also allows me to create new genre's without opening a separate form. Similar to the way free tagging works in a cms website like Drupal or Wordpress.
My Attempt 1
I have successfully created a form that allows me to display all tags using a sub-form pointing to the movie_genres table and a combo box pointing to the genre table. This form setup also allows me to select existing values as new genres. It does not however allow me to create new genre's.
In this form if I type a value not present I get the warning "The text you entered isn't an item in the list."
If I attempt to change the combo box to "Limit To List: No" I get the warning: "The first visible column... isn't equal to the bound column." If I make the first visible column the bound column the combo box simply displays numbers and not names, which is silly because the information is there either way.
The form for this simplified case looks like:
My attempt 2
I can also create a subform that points to both the movie_genres and genres tables with a regular textbox pointing to genre name. This allows me to create new values but it does not let me select from existing values. No pic of this one.
Creating a combo box on this form act identical to the second form.
The question again
How can I create a movie form item that supports both creation and listing existing genres?
You can easily add new values to the list of genres using 'NotInList' event. Leave Limit To List: Yes and use code similar to code below:
Private Sub GenreName_NotInList(NewData As String, Response As Integer)
' Prompt user to verify they wish to add new value.
If MsgBox("Genre '" & NewData & "' is not in list. Add it?", _
vbOKCancel) = vbOK Then
' Set Response argument to indicate that data
' is being added.
Response = acDataErrAdded
' Add string in NewData argument to row source.
DoCmd.SetWarnings False
DoCmd.RunSQL "INSERT INTO Genres (GenreName) SELECT '" & NewData & "';"
DoCmd.SetWarnings True
Else
' If user chooses Cancel, suppress error message
' and undo changes.
Response = acDataErrContinue
Me.GenreName.Undo
End If
End Sub

Most efficient database schema for counting keywords

I'm working on an iPhone app with a GAE backend. I currently have a database of ~8000 products and each product has 5 keywords, mined from reviews, that are the words used most often to describe the product. Once I deploy the app, I'd like to allow users to add new products, and add their 5 keywords to existing products. So, when "reviewing" an existing product, they would add their 5 words, and these would be reflected in the Top 5 words if they push a word over into the Top 5. These keywords will be selected via a large whitelist with indirect selection so I can control the user input. I'd like the application to scale to thousands of users without hitting my backend too hard.
My question is:
What's the most efficient database schema for keeping track of all the words for a product and calculating the top 5 for each product once it's updated?
My two ideas (which may be terrible):
Have a "words" column which contains a 2d array, one dimension is the word, the other is the count for that word. They would then be incremented/decremented as needed.
Have a database with each word as a column and each product as a row and the corresponding row/column would contain the count.
The easiest way to do this would be to have a 'tags' kind, defined something like this (you haven't specified a backend language, so I'm assuming Python):
class Tag(db.Model):
# Tags should be child entities of Products and have key name based on the tag
# eg, created with Tag(parent=a_product, key_name='awesome', ...)
count = db.IntegerProperty(required=True, default=0)
#classmethod
def increment_tags(cls, product, tag_names):
def _tx():
tags = cls.get_by_key_name(tag_names, parent=product)
for i, tag in enumerate(tags):
if tag is None:
# New tag
tags[i] = tag = cls(key_name=tag_names[i], parent=product)
tag.count += 1
db.put(tags)
return db.run_in_transaction(_tx)
#classmethod
def get_top_product_tags(cls, product, num=5):
return [x.key().name() for x
in cls.all().ancestor(product).order('-count').fetch(num)]
The increment_tags method increments the count property on all the relevant tags. Since they all have the same parent entity, they're in the same entity group, and it can do this transactionally, in a single transaction.
The get_top_product_tags method does a simple datastore query to find the num top ranked tags for a product.
You should use a normalized schema and let SQL and the database engine be your friend. Have a single table with a design like this:
create table KeywordUse
( AppID int
, UserID int
, Sequence int
, Word varchar(50) -- or whatever makes sense
)
You can also have an identity primary key if you like, but AppID + UserID + Sequence is a candidate key (i.e. the combination of these three must be unique).
To find the top 5 keywords for any app, do a SQL query like this:
select top 5
count(AppID) as Frequency -- If you have an identity PK count that instead.
, Word
from KeywordUse
where AppID = #AppIDVariable...
group by Word, AppID
order by count(AppID) desc
If you are really, really worried about performance you could denormalize the results of this query into a table that shows the words for each app. Then you'd have to work out how often to refresh that snapshot.
REVISED ANSWER:
As Nick Johnson so generously pointed out, aggregate functions are not available in GQL. However, the philosophy of my answer remains unchanged. Let the database engine do its job.
The table should be AppID, Word, and Frequency. (AppID and Word are the PK.) Then each use of the word would be added up as it is applied. Then, when you want to know the top five words for an app you select by AppID := #Value and order by Frequency (descending) with a LIMIT = 5.
You would need a separate table to track user keywords if that is important.