How/when to query 'extended' entities in Breeze - asp.net-mvc

I have a ViewModel that loads up 'child' entities and I want to also display 'grandchild' entities based off of each child that is loaded. To simplify things, I need help identifying how to query these objects and display them under the proper 'tree' in the browser (apologies for my butchering of coding language : ))
I am using Knockout to bind the data and loading up the entities with Breeze. This question is an extension of When to add extend additional complex types onto a Breeze entity
Also - my model is EF code first and I have a configuration defining a one to many relationship between children and grandchildren, and I think Breeze knows this already but I am trying to figure out how to take advantage of this.
childs.js (view model)
var childs = ko.observableArray();
var grandChilds = ko.observableArray();
var parentId = ko.observable();
function refresh() {
var parentId = (parent).parentId; // << for ex. don't worry about this line : )
return Q.all([getChildren(), getGrandChildren()]);
}
function getChildren() {
return datacontext.getChildren(childs, parentId);
}
function getGrandChildren() {
return datacontext.getGrandChildren(grandChilds);
}
and in the view (childs.html)
<div data-bind="foreach: childs">
<div title="Go to Child Details">
<div><strong data-bind="text: name"></strong></div>
<div><strong data-bind="text: gender().description"></strong></div>
</div>
<div>
<!-- ko.compose { view: grandChilds} --><!--/ko-->
</div>
</div>
And my current datacontext for reference
var getChilds= function (childsObservable, parentId) {
var query = EntityQuery.from('Childs')
.where('parentId', '==', parentId)
.expand('grandChildren')
.orderBy('id');
return manager.executeQuery(query)
.then(querySucceeded)
.fail(queryFailed);
function querySucceeded(data) {
if (childsObservable) {
childsObservable(data.results);
}
logger.log('Retrieved [Childs] and [Grandchilds] from remote data source', data, system.getModuleId(datacontext), true);
}
};
I want to load up only grandchildren of the children, and since there are many children I want to only display grandchildren under the correct child, not all grandchildren in one list. Any help would be appreciated.

You have three basic approaches to querying and "linking" related entities.
1) Use EntityQuery.expand
2) Use EntityAspect.loadNavigationProperty
3) Create a "broad" EntityQuery that just happens to encompass the entire graph and all of the parent/child relations will be automatically linked.

Related

Loading parent and child nodes from remote data

I've got a method in my controller that returns a List<TreeViewItemModel>() that I'm populating with the correct hierarchy. This seems to serialize correctly, but when I load the Treeview, I don't have any of the hierarchy, just the first level of nodes.
Example:
Each of the above Curricula has 2/3 scenarios underneath that I've verified are getting added as items to the base object when going from curriculum => TreeViewItemModel
Controller:
public JsonResult GetAvailableCurricula(string LocationId)
{
LocationId = "1";
if(LocationId != string.Empty)
{
var results = Logic.GetFilteredCurriculum().Select(c => CurriculumToTreeView(c));
return Json(results, JsonRequestBehavior.AllowGet);
}
else
{
return Json(new List<TreeViewItemModel>(),JsonRequestBehavior.AllowGet);
}
}
private TreeViewItemModel CurriculumToTreeView(CurriculumModel c)
{
var tree = new TreeViewItemModel()
{
Id = c.CurriculumId.ToString(),
Text = c.CurriculumName,
HasChildren = c.Scenarios.Any()
};
if (tree.HasChildren)
{
tree.Items = c.Scenarios.Select(scenario =>
new TreeViewItemModel()
{
Text = scenario.Name,
}
).ToList();
}
return tree;
}
View:
#(Html.Kendo().TreeView()
.Name("AvailableCurricula")
.DataTextField("Text")
.DataSource(source => source
.Read(read => read
.Action("GetAvailableCurricula", "TraineeAssignments")
.Data("filterAvailableCurricula")
)
)
Is there some extra step I need to take to bind the child objects AND the parent, instead of just one level at a time? I have a fairly small set of data that I don't need to reload all that often, so I would was hoping to avoid loading each level individually/on-demand.
In case it's helpful, here's the raw JSON I'm sending from the controller for one of my curricula:
{"Enabled":true,"Expanded":false,"Encoded":true,"Selected":false,"Text":"Operator B","SpriteCssClass":null,"Id":"1","Url":null,"ImageUrl":null,"HasChildren":true,"Checked":false,"Items":[{"Enabled":true,"Expanded":false,"Encoded":true,"Selected":false,"Text":"test 2","SpriteCssClass":null,"Id":null,"Url":null,"ImageUrl":null,"HasChildren":false,"Checked":false,"Items":[],"HtmlAttributes":{},"ImageHtmlAttributes":{},"LinkHtmlAttributes":{}},{"Enabled":true,"Expanded":false,"Encoded":true,"Selected":false,"Text":"Scenario II","SpriteCssClass":null,"Id":null,"Url":null,"ImageUrl":null,"HasChildren":false,"Checked":false,"Items":[],"HtmlAttributes":{},"ImageHtmlAttributes":{},"LinkHtmlAttributes":{}}],"HtmlAttributes":{},"ImageHtmlAttributes":{},"LinkHtmlAttributes":{}}
I believe that the remote data option for the Treeview uses ajax to load the child data, either on demand or at initial load - controlled by the LoadOnDemand option.
The remote data examples in the kendo docs behave that way. That is how I implemented it on a previous project. The full code example includes a treeview as well as a grid.

View Renders before Knockout Binds Data

I am sure this has been asked before but alas I can't find it - any help to point me in the right direction would be greatly appreciated.
I am loading a view / view model with Durandal and during the Activate method I am calling for a single record to be fetched and then displayed. I am getting the record back (checked the XHR response and all data comes back ok) but I can only assume that the view is loading before the data is ready to display. No JS errors, no errors at all for that matter, but just a big whitespace in the middle of my screen, even where I know data should show...
ViewModel :
define(['durandal/system', 'services/logger', 'services/datacontext'], function (system, logger, datacontext) {
var aForm = ko.observable();
var initialized = false;
function activate(routeData) {
var id = parseInt(routeData.id);
return refresh(id);
};
function refresh(id) {
return datacontext.getaFormById(id, aForm);
}
var vm = {
activate: activate,
aForm: aForm,
title: "THE TITLE DISPLAYS JUST FINE"
}
return vm;
});
View :
<h3 class="page-title" data-bind="text: title"></h3>
<div class="container-fluid" data-bind="with: aForm">
<div class="row-fluid">
<div class="span12">
<strong>Testing</strong>
<strong data-bind="text: id"></strong>
</div>
</div>
<h2 data-bind="text: description"></h2>
<h2 data-bind="text: checkType().description"></h2>
</div>
I threw in the Testing strong and it doesn't even render, only the title does. Can anyone point me in the right direction? I would create a fiddle but it works when I hardcode the data in the ViewModel.
EDIT :
Ok after digging into it a bit more it is possible I am not returning the object properly, specifically in the data.entity return type. Would this cause the issue?
var getaFormById = function (aFormId, aFormObservable) {
var query = EntityQuery.from('aForms')
.where('id', '==', aFormId);
return manager.executeQuery(query)
.then(querySucceeded)
.fail(queryFailed);
function querySucceeded(data) {
if (aObservable) {
aObservable(data.entity);
}
logger.log('Retrieved selected [aForm] from remote data source', data, system.getModuleId(datacontext), true);
}
}
You are not correctly filling your observable in your executeQuery success callback that is why your UI is not rendered correctly.
From the executeQuery documenation the successFunction called with the following argument
successFunction([data])
data Object
results Array of Entity
...
So you need to fill your observable from the data.results array and not form data.entity (which just returns undefined):
if (aObservable) {
aObservable(data.results[0]);
}
You can tell Durandal to hold off binding by returning a jQuery promise() from the activate function.
See this video by Ryan Keeter for the explanation: http://www.youtube.com/watch?v=w_XjWg6xL8I

InvalidOperationException when using updatemodel with EF4.3.1

When I update my model I get an error on a child relation which I also try to update.
My model, say Order has a releationship with OrderItem. In my view I have the details of the order together with an editortemplate for the orderitems. When I update the data the link to Order is null but the orderid is filled, so it should be able to link it, TryUpdateModel returns true, the save however fails with:
InvalidOperationException: The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.]
My update method:
public ActionResult ChangeOrder(Order model)
{
var order = this.orderRepository.GetOrder(model.OrderId);
if (ModelState.IsValid)
{
var success = this.TryUpdateModel(order);
}
this.orderRepository.Save();
return this.View(order);
}
I tried all solutions I saw on SO and other sources, none succeeded.
I use .Net MVC 3, EF 4.3.1 together with DBContext.
There are a number of code smells here, which I'll try to be elegant with when correcting :)
I can only assume that "Order" is your EF entity? If so, I would highly recommend keeping it separate from the view by creating a view model for your form and copying the data in to it. Your view model should really only contain properties that your form will be using or manipulating.
I also presume orderRepository.GetOrder() is a data layer call that retrieves an order from a data store?
You are also declaring potentially unused variables. "var order =" will be loaded even if your model is invalid, and "var success =" is never used.
TryUpdateModel and UpdateModel aren't very robust for real-world programming. I'm not entirely convinced they should be there at all, if I'm honest. I generally use a more abstracted approach, such as the service / factory pattern. It's more work, but gives you a lot more control.
In your case, I would recommend the following pattern. There's minimal abstraction, but it still gives you more control than using TryUpdateModel / UpdateModel:
public ActionResult ChangeOrder(OrderViewModel model) {
if(ModelState.IsValid) {
// Retrieve original order
var order = orderRepository.GetOrder(model.OrderId);
// Update primitive properties
order.Property1 = model.Property1;
order.Property2 = model.Property2;
order.Property3 = model.Property3;
order.Property4 = model.Property4;
// Update collections manually
order.Collection1 = model.Collection1.Select(x => new Collection1Item {
Prop1 = x.Prop1,
Prop2 = x.Prop2
});
try {
// Save to repository
orderRepository.SaveOrder(order);
} catch (Exception ex) {
ModelState.AddModelError("", ex.Message);
return View(model);
}
return RedirectToAction("SuccessAction");
}
return View(model);
}
Not ideal, but it should serve you a bit better...
I refer you to this post, which is similar.
I assume that the user can perform the following actions in your view:
Modify order (header) data
Delete an existing order item
Modify order item data
Add a new order item
To do a correct update of the changed object graph (order + list of order items) you need to deal with all four cases. TryUpdateModel won't be able to perform a correct update of the object graph in the database.
I write the following code directly using a context. You can abstract the use of the context away into your repository. Make sure that you use the same context instance in every repository that is involved in the following code.
public ActionResult ChangeOrder(Order model)
{
if (ModelState.IsValid)
{
// load the order from DB INCLUDING the current order items in the DB
var orderInDB = context.Orders.Include(o => o.OrderItems)
.Single(o => o.OrderId == model.OrderId);
// (1) Update modified order header properties
context.Entry(orderInDB).CurrentValues.SetValues(model);
// (2) Delete the order items from the DB
// that have been removed in the view
foreach (var item in orderInDB.OrderItems.ToList())
{
if (!model.OrderItems.Any(oi => oi.OrderItemId == item.OrderItemId))
context.OrderItems.Remove(item);
// Omitting this call "Remove from context/DB" causes
// the exception you are having
}
foreach (var item in model.OrderItems)
{
var orderItem = orderInDB.OrderItems
.SingleOrDefault(oi => oi.OrderItemId == item.OrderItemId);
if (orderItem != null)
{
// (3) Existing order item: Update modified item properties
context.Entry(orderItem).CurrentValues.SetValues(item);
}
else
{
// (4) New order item: Add it
orderInDB.OrderItems.Add(item);
}
}
context.SaveChanges();
return RedirectToAction("Index"); // or some other view
}
return View(model);
}

Saving nested objects with linq to entities

I have a UI that presents a number of checkboxes to the user, and for each one that is checked, I need to create an entry in a mapping table.
LookupTable <- MapTable -> DataTable
I have a custom binder for DataTable, but can't figure out how to get it to create the MapTable objects.
Is this possible? Using asp.net MVC 1.0 and LINQ to Entities.
You need to take care of two steps. (1) Add the newly selected values and (2) remove the unselected values. You'll need a method like this in your LookupTable class.
public void SynchronizeDataTables(IEnumerable<DataTable> dataTables)
{
// get the current data tables. call ToList() to force and enumeration.
// without the ToList(), you'll get a "Sequence Changed during Enumeration"
// error
var currentDataTables = MapTable.Select(m => m.DataTable).ToList();
// if the table is selected, but not in the data store add it.
foreach (var dataTable in dataTables)
{
if (!currentDataTables.Contains(dataTable))
{
MapTables.Add(new MapTable { DataTable = dataTable });
}
}
// if the table is in the data store, but not selected, then remove it.
foreach (var dataTable in currentDataTables)
{
if (!dataTables.Contains(dataTable))
{
MapTables.Remove(dataTable);
}
}
}
Edit: When I did this, I was using LINQ-to-SQL, and I cycled through just the selected ID's, instead of the entire object. This is more complicated because LINQ-to-Entities creates slightly different objects than LINQ-to-SQL, because it doesn't expose the FK identity. Slight modification follows:
public void SynchronizeDataTables(IEnumerable<int> dataTableIds)
{
// get the current data tables. call ToList() to force and enumeration.
// without the ToList(), you'll get a "Sequence Changed during Enumeration"
// error
var currentDataTableIds = MapTable.Select(m => m.DataTable.Id).ToList();
// if the table is selected, but not in the data store add it.
foreach (var dataTableId in dataTableIds)
{
if (!currentDataTableIds.Contains(dataTableId))
{
var dataTable = ???; // some method to fetch data table with ID = dataTableId
MapTables.Add(new MapTable { DataTable = dataTable });
}
}
// if the table is in the data store, but not selected, then remove it.
foreach (var dataTable in currentDataTableIds )
{
if (!dataTableIds.Contains(dataTableId ))
{
var dataTable = ???; // some method to fetch data table with ID = dataTableId
MapTables.Remove(dataTable);
}
}
}

MVC, UpdateModel OR delete depending on form field value?

I'm very new to this, so any help is appreciated.
I'll use the Dinners/RSVPs relationship for detailing my problem. One Dinner has many RSVPs.
On my Dinner edit page/view I want to be able to edit the Dinner information AND the RSVPs information.
I have that part working, based on the answer given here by James S:
int i = 0;
foreach (var r in Dinner.RSVPs) {
UpdateModel(r, "Dinner.RSVPs[" + i++ + "]");
}
But what if I want to Delete an RSVP based on the user clicking a checkbox next to the RSVP on the edit view? Something like this on the edit view:
<% int i = 0;
foreach (var rsvp in Model.RSVPs){%>
<%=Html.CheckBox("RemoveRSVP[" + i + "]") %>
<%= Html.TextBox("Dinner.RSVPs[" + i + "].Name", rsvp.Name) %>
<% i++;
}%>
I tried this, but it's not working, obviously:
Dinner dinner = dinnerRepository.GetDinner(id);
int i = 0;
foreach (var r in dinner.RSVPs) {
if (Boolean.Equals(RemoveRSVP[i], true){
dinner.RSVPs.Remove(r);
else
UpdateModel(r, "Dinner.RSVPs[" + i+ + "]");
i++;
}
I can't delete/remove an RSVP using UpdateModel can I?
Let me know if anything isn't clear.
Thanks.
I tried this, but it's not working, obviously:
Is your difficulty in actually making the delete go through? Or is it in processing the form to detect which ones should be deleted? e.g. which line doesn't work:
dinner.RSVPs.Remove(r);
or
if (Boolean.Equals(RemoveRSVP[i], true)
?
For #1
If your repository is backed by Linq 2 Sql and RSVP is an entity, you will usually have to cause DeleteOnSubmit() to be called in order for the record to be deleted from the database--just calling Remove() on the association will not be enough. You probably will add one of the following to your DinnerRepository to do this:
DinnerRepository.DeleteRsvp(RSVP item)
DinnerRepository.DeleteRsvp(Dinner dinner, RSVP rsvp)
Alternately, if you want LINQ to perform the delete automatically, you can edit the DBML as XML (right click, open with, XML Editor) and add the following attribute to the entity association:
<Association Name="..." ... DeleteOnNull="true" />
For #2
I usually construct this type of "repeating entity-delete checkbox" form so that the posted values are a list of the entity IDs I want to delete. To facilitate this I use an alternate CheckBox helper:
public static class HtmlExtensions
{
/// <summary>
/// Alternate CheckBox helper allowing direct specification of "name", "value" and "checked" attributes.
/// </summary>
public static string CheckBox(this HtmlHelper html, string name, string value, bool isChecked)
{
string tag = String.Format("<input type=\"checkbox\" name=\"{0}\" value=\"{1}\" {2}/>",
html.AttributeEncode(name),
html.AttributeEncode(value),
isChecked ? "checked=\"checked\" " : ""
);
return tag;
}
}
and create the checkboxes like so:
<%= Html.CheckBox("RemoveRsvpIds", rsvp.RsvpId.ToString(), false) %>
and consume the list like so:
public ActionResult TheFormInQuestion(int dinnerId, int[] removeRsvpIds)
{
var dinner = DinnerRepository.GetDinner(dinnerId);
foreach (var rsvp in dinner.RSVPs)
{
if (removeRsvpIds.Contains(rsvp.RsvpId))
{
// Perform Delete
}
else
{
// Perform Update
}
}
// The rest
}
I can't delete/remove an RSVP using UpdateModel can I?
The purpose of UpdateModel() is to automagically copy property values from the posted form onto an already-existing object--not to create new or destroy existing entities. So no, not really. It wouldn't be the expected behavior.
I am not totally familiar with the NerdDinner code but don't they use Linq to SQL for their backend? If that is the case I would think you could tackle this in a traditional web approach and append the record ID to the value of each check box in a list of items to be deleted. Then you could catch the collection of IDs on the server side and do a DeleteAllOnSubmit by passing a selection query of entities to the delete call? Let me know if you need more detail.

Resources