I have a problem with MVC displaying list of many to one objects using an http post. How do I perform a db.SaveChanges() so that it includes each claw from my form submit?
example primary entity:
Cats table has
Cats: id, and cat name only.
many to one cat entity (notice CatId):
Paws: Paw Number, claw1, claw2, claw3, claw4, claw5, and finally CatId
each claw number represents a sharpness index.
On my main form I have only a single cat and have all 4 paws and its sharpness index listed out.
Now if I want to save each of the 4 paws and claws for this one cat how do I get save db.SaveChanges() if there is no it pointing to Paws in the Cats table. This seems so basic but haven't been able to tweak it yet. I've even set the #Html.ForEditor control to have an id of Paws and even Paws.Claws or Paws.Claw doesn't seem to work.
I'm trying to use MVC 4.5 for this.
Related
The documentation describes a meta collection as a combination of 2 (or more) different APIs...
By default, a meta API endpoint returns all data from all of its
sub-APIs, organized by collection.
But, what I find is that it does not do this. It grabs partial data from some sub-APIs and fails silently, without logging an error.
API #1 Result
COLLECTION2
ROW LIST.HREF LIST.TEXT INDEX URL
1 http://www.amazon.com/Org...pollux+organix+canned+dog Canned Dog Food 3 http://www.austinpetsalive.org/donate/wish-list/
2 http://www.amazon.com/Pre...s-Large/lm/R34ISSXSRJPA71 Premier Brand Martingale collars (Pink, Silver, Blue, Red, and Orange) sizes XL or L 4 http://www.austinpetsalive.org/donate/wish-list/
3 http://www.amazon.com/Pre...ords=medium+gentle+leader Medium & Large Gentle Leaders 5 http://www.austinpetsalive.org/donate/wish-list/
API #2 Result
COLLECTION2
ROW LIST.HREF LIST.TEXT INDEX URL
1 Dry kitten and adult dog food (we ask that the first ingredient listed on the bag be meat). Some Brands we love include: Purina One, Pro-Plan, Wellness, Evolve, Blue Buffalo, and Kirklands 9 http://pawsshelter.org/donate/wishlist/
2 Cat Litter 10 http://pawsshelter.org/donate/wishlist/
3 Kongs, Balls, Durable Toys, Puzzle Toys 11 http://pawsshelter.org/donate/wishlist/
Meta API Result Collection 2 -- it's the entire data set from API #2 and none from API #1
COLLECTION2
ROW LIST.HREF LIST.TEXT INDEX URL API
1 Dry kitten and adult dog food (we ask that the first ingredient listed on the bag be meat). Some Brands we love include: Purina One, Pro-Plan, Wellness, Evolve, Blue Buffalo, and Kirklands 132 http://pawsshelter.org/donate/wishlist/ PAWS Shelter and Humane Society
2 Cat Litter 133 http://pawsshelter.org/donate/wishlist/ PAWS Shelter and Humane Society
3 Kongs, Balls, Durable Toys, Puzzle Toys 134 http://pawsshelter.org/donate/wishlist/ PAWS Shelter and Humane Society
The data structure is verbatim the same. Why don't they combine under meta API?
Testing
A meta API combination worked with 2 APIs, each with one collection.
When there is more than one collection defined, certain combinations of APIS combined partially. Each collection filled with the contents of one or the other API, but never both.
The 3 APIs I need to combine result in one site's results in all of the collections, and nothing from the other two in any collection, and no error logged.
The flaky results seem tied to the collections. But I've moved on to a klugey temp fix, which is to call each API separately and combine the JSON results in my app. 3 API calls instead of one. Might be looking for another tool, soon.
Now it works
Since I posted this question in October, KimonoLabs has updated their app and I am now having consistent success with creating and using a Meta API for the set of single APIs I posted above.
That's the positive.
The catch is that you cannot use the URL parameters in a meta API, so if you'd written post-process modify results functions, they will not be executed, even if you use kimmodify=1.
Let's say I have the following entities in my libraries app - Library Room, shelf, Book.
Where Room has N shelves, and shelves have N Books.
Now the following url brings me a list of books whose
library is 3, room no. is 5 and shelf no. is 43.
.../library/3/room/5/shelf/43/books
Assuming shelf 43 is unique per room only
(There is shelf 43 also in other rooms)
and Rooms are not unique (There's a few room no. 5 ) in the library.
Here is my questions:
I want to filter with more fields on the entities, here is what i want to do
(representation not in rest):
.../library/id=3&type=3/room/decade=21&topic=horror/shelf/location=east&/books
This is not rest.
How do I represent it in rest?
Notes:
I don't want to do this way
.../books¶m1=X¶m2=X¶m3=X¶m4=X
because not all params are related to books.
Couple of things that you need to look into while designing your apis.
1) are type, decade, topic etc required fields? if so, I will probably make them a part of the path itself, such as:
../libraries/{libraryId}/type/{typeId}/rooms/{roomId}/decades/{decadeId}/topics/{topicName}/shelves/{shelfId}/locations/{shelfLocation}/books
Here I am assuming that each library can have rooms which have unique room ids per library, each room can have shelves which has unique ids/locations per room (and so on and so forth). Yes, the url is pretty long, but that's kind of expected
2) if these fields are not required, you could use a different approach which is a bit less verbose but a bit more confusing for client developers who have never used such approach here. Here's a straight up example Restful Java with JAX-RS by Bill Burke
#Path("{first}-{last}")
#GET
#Produces("application/xml")
public StreamingOutput getCustomer(#PathParam("first") String firstName,
#PathParam("last") String lastName) {
...
}
Here, we have the URI path parameters {first} and {last}. If our HTTP request is
GET /customers/bill-burke, bill will be injected into the firstName parameter and
burke will be injected into the lastName parameter.
If we follow this somewhat academic approach (I have not seen this implemented on many platforms. Most platforms normally go with approach # 1, a more verbose but clear approach), your URL would look somewhat like this:
../libraries/{libraryId}-{typeId}/rooms/{roomId}-{decadeId}-{topicName}/shelves/{shelfId}-{shelfLocation}/books
This way, if the client developer doesn't pass in the non-required fields, you can handle it at the business logic level and assign these variables a default value, for example:
../libraries/3-/rooms/2-1-horror/shelves/1-/books
With this url, libraryId = 3, typeId = null (thus can be defaulted to it's default value) and so on and so forth. Remember that if libraryId is required field, then you might want to actually make it a part of the pathparam itself
Hope this helps!
Hi guys I have a situation where on a form I'm taking in orders for a car servicing application. I have the following models:
Car
belongs_to :car_company
Car_company
has_many :cars
Services
attributes_accessible :car_company_id, :car_id
#virtual attributes
attributes_accessible :car_company_name, :car_reg
The thing is that on a single form the user can enter in the name of the car company as well as the registration number of a car. If the company name doesnt exist it creates a new company and associates it with the service and the same goes for the car. I got this part working however the thing is that I want that on submitting this form the car created should be automatically associated with the car_company whether the carcompany exists or doesn't exist.
I'm pretty stuck here on how to get this thing done the right way? Its basically just to avoid having to enter the car details and the company details seperately just to use them on a form. Any ideas guys?
I see you are using an unconventional model name. By convention in rails, your model should be CarCompany. However, I think what you have will work.
Putting something like this in the appropriate controller may be something like what you want. If not, please clarify what you want.
car_company = Car_company.find_or_initialize_by_name(params[:car_company_name])
car = Car.find_or_initialize_by_registration(params[:car_registration])
car_company.cars << car
car_company.save
You actually may be able to combine the middle two lines with car_company.cars.find_or..., but I'm not sure if that works or not.
I hope that helps.
Hiiii,
I am developing a small app using Restlet 2.0 API..
I want just to know how to create a URI which accepts more than one parameter for insert query.
Ex:
router.attach("/{patient}/insertpatient", insertpatient);
I want to insert all the info about the patient using POST.
Or Search by ID and address for instance using GET.
thanks,
For the "insert patient" operation, I'd suggest something like a POST to /patients (if the server generates the patient ID) or a PUT to /patients/{patient-id} (if the client generates the patient ID). Either way, the body of the message would contain all of the input data needed to create a new patient entity. Two simple options for serializing the data would be as a URL-encoded form or as JSON.
Lookup by by ID could be a simple as a GET on /patients/{patient-id}. Lookup by address could also be a GET, possibly using a URL-encoded query parameter. For example, you could fetch the patient at address "123 Main Street, apt 4, Anytown, USA, 98765" with a GET on /patients?addr=%20Main%20Street%2C%20apt%204%2C%20Anytown%2C%20USA%2C%2098765
I would like to return a DTO from my data layer which would also contain child collections...such as this:
Audio
- Title
- Description
- Filename
- Tags
- TagName
- Comments
- PersonName
- CommentText
Here is a basic query so far, but i'm not sure how to transform the child collections from my entity to the DTO.
var query = Session.CreateCriteria<Audio>("audio")
.SetProjection(
Projections.ProjectionList()
.Add(Projections.Property<Audio>(x => x.Title))
.Add(Projections.Property<Audio>(x => x.Description))
.Add(Projections.Property<Audio>(x => x.Filename))
).SetResultTransformer(new AliasToBeanResultTransformer(typeof(AudioDto)))
.List<AudioDto>();
Is this even possible, or is there another reccomended way of doing this?
UPDATE:
Just want to add a little more information about my scenario...I want to return a list of Audio items to the currently logged in user along with some associated entities such as tags, comments etc...these are fairly straight forward using MultiQuery / Future.
However, when displaying the audio items to the user, i also want to display 3 other options to the user:
Weather they have added this audio item to their list of favourites
Weather they have given this audio the 'thumbs up'
Weather the logged in user is 'Following' the owner of this audio
Favourites : Audio -> HasMany -> AudioUserFavourites
Thumbs Up : Audio -> HasManyToMany -> UserAccount
Following Owner : Audio -> References -> UserAccount ->
ManyToMany -> UserAccount
Hope this makes sense...if not i'll try and explain again...how can I eager load these extra details for each Audio entity returned...I need all this information in pages of 20 also.
I looked at Batch fetching, but this appears to fetch ALL thumbs ups for each Audio entity, rather than checking if only the logged in user has thumbed it.
Sorry for rambling :-)
Paul
If you want to fetch your Audio objects with both the Tags collection and Comments collections populated, have a look at Aydende Rahien's blog: http://ayende.com/blog/4367/eagerly-loading-entity-associations-efficiently-with-nhibernate.
You don't need to use DTOs for this; you can get back a list of Audio with its collections even if the collections are lazily loaded by default. You would create two future queries; the first will fetch Audio joined to Tags, and the second will fetch Audio joined to Comments. It works because by the time the second query result is being processed, the session cache already has the Audio objects in it; NHibernate grabs the Audio from the cache instead of rehydrating it, and then fills in the second collection.
You don't need to use future queries for this; it still works if you just execute the two queries sequentially, but using futures will result in just one round trip to the database, making it faster.