Storing a complex detached object graph in EF6 - entity-framework

I have the current scenario:
I'm using EF6 Code first, and have created a data-model something like this:
public class MainObject{
..some properties
IList<SubObject> SubObjects{get;set;}
}
public class SubObject{
..some properties
IList<SubSubObject> SubSubObjects{get;set;}
}
public class SubObject{
..some properties
IList<SubObject> SubObjects{get;set;}
}
So basically I have a main object, that has 0 to many subobjects, and there is a many to many relationship between the subobject and the subsubobjects.
I am creating a MVC application, so my normal program flow is that the user request a page that basically uses a MainObject as it's data model. Then the user interacts with the page and changes, adds or removes subobjects and subsubobjects as he wishes, and then clicks save. On save, the objectgraph is sent back to the controller and it looks correct according to the changes done by the user on the client side. Now my problem is the following:
How to store this back into the database in a good fashion.
I need to attach my object back into the context, but I have no clue which objects are new, modified or deleted.
I have written some code that partially works now, but it's getting so ugly that I really don't want to go down that path. Would it be possible somehow to fetch the relevant object graph from the database, and have EF compare the two graphs toward eachother, and then save the relevant changes to the database?
Any help to make this smoother would be greatly appreciated.

I ended up using GraphDiff to solve this for me, and it works just great! This really should be built into EF, but untill it does, this is a great substitute.
To solve the example given in my question above, this will make sure that the detached graph gets saved properly (given I have a MainObject I want to save called main):
context.UpdateGraph(main, map =>map
.AssociatedCollection( m => m.SubObjects, with => with
.AssociatedCollection( s => s.SubSubObjects)
)
);
context.SaveChanges();

Related

Working with Swift and Core Data

This is more of a generalized question as I have yet to write the code for the question I am asking. Before I get started writing the code I wanted to make sure I am on the right track and possibly getting suggestions for better ways to do what I want to do. Basically right now I have a core data model setup in a way that I think is correct for what I am trying to do and just need some guidance on a very specific part of the code but want to make sure overall I created it correctly.
The first part to the question is more of a clarification on how relationships work in core data. Right now I have 5 entities and to make sure I have the correct idea on how it works I will use a few examples to make sure I am on the right track.
So lets save I have an entity I called name. Within that Name entity that contains only a name attribute. Next I have an entity that has classes, that each have a boolean of true or false to determine which class it is. These 2 are related in a inverse relationship of Name entity having a to one relationship and the Classes having a to many relationship because multiple names can have multiple classes but each name can only have 1 class. If I am right on this one that means I full understand core data relationships!
Now the second part of the question is related to the booleans in the class. I have the Class entity which is like I said a boolean containing a true false set as default to false. When the user selects one of the class buttons before presenting the popover where they actually give the name of the class selected it saves the boolean to true then passes that data over to the popover Name view controller. I am very unsure as to how to do this as it isn't a widely asked question on here nor have I been able to find any info through researching. I am one of those people who needs to actually learn by clear examples....any help with this would be appreciated! Sorry I don't have any example code for this.
The first part seems correct. The ManagedObject of your Class CoreDataObject should have an NSSet property which will contain the names (as the Class can have multiple names)
For the second part, Core Data uses objects. When you 'get' the data from Core Data it will be a (probably extended) NSManagedObject (named Class in our case). You can send this object as a parameter just as you would do with any other object and use it as you would use any other object :-). For example looping over de NSSet Names
func iterateOverNames(someClass: Class) {
for name: Name in someClass.names {
// do stuff
}
}
You can check these links for more information:
https://realm.io/news/jesse-squires-core-data-swift/
https://developer.apple.com/library/ios/documentation/Cocoa/Reference/CoreDataFramework/Classes/NSManagedObject_Class/index.html

What gets send to the server with request factory

I have problem to understand what does Request factory send to server. I have a method
Request<NodeProxy> persist(NodeProxy node)
NodeProxy is an Object from tree like structure (has child nodes and one parent node, all of type NodeProxy). I'v change only one attribute in the node and called persists.
The question now is what gets send to the server?
In the dock here https://developers.google.com/web-toolkit/doc/latest/DevGuideRequestFactory
there is:
"On the client side, RequestFactory keeps track of objects that have been modified and sends only changes to the server, which results in very lightweight network payloads."
In the same dock, in the chapter Entity Relationships, there is also this:
"RequestFactory automatically sends the whole object graph in a single request."
And I'm wondering how should I understand this.
My problem:
My tree structure can get quete big, lets say 50 nodes. The problem is that for update of one attribute the method
public IEntity find(Class<? extends IEntity> clazz, String id)
in the class
public class BaseEntityLocator extends Locator<IEntity, String>
gets called for each object in the graph which is not acceptable.
Thank you in advance.
The problem you're facing is that RequestFactory automatically edit()s proxies when getting properties, and there's a bug when constructing the request payload that makes the whole graph of proxies to be implicitly edited that way, even if you didn't call the getter yourself.
That bug has many repercussions, including false-positives in RequestContext's isChanged(): http://code.google.com/p/google-web-toolkit/issues/detail?id=5952
I have great hopes that this will be fixed in GWT 2.5 (due in the next weeks).

Magento: Accessing models/blocks from a phtml

Hi I have a situation where I need to look up the number of recently viewed products on catalog/product/view.phtml. In the recently viewed 'product_viewed.phtml' file it calls
$_products = $this->getRecentlyViewedProducts()
to get the recently viewed. How would I access this method from within the catalog/product/view.phtml file?
I don't know where this method is. I've tried searching for it but it doesn't seem to exist. When I write click it in Netbeans and click go to declaration it takes me to
class Mage_Reports_Block_Product_Viewed extends Mage_Reports_Block_Product_Abstract
Actually on the class itself. This class only has _toHtml(), getCount(), and getPageSize() methods.
I just need to know whether there are any recently viewed products.
Any help most appreciated!
Billy
If you look into 'Mage_Reports_Block_Product_Viewed', you will notice:
$this->setRecentlyViewedProducts($this->getItemsCollection());
That 'getItemsCollection' method is defined in the abstract class... And you will notice this abstract class will create a model based on $_indexName defined in the (subclassed) block.
If you just want the collection, you can probably get away with:
$_products = Mage::getModel('reports/product_index_viewed')->getCollection();
And then adding whatever you want to the collection:
$_products
->addAttributeToSelect('*')
->setAddedAtOrder();
// optionally add other methods similar to Mage_Reports_Block_Product_Abstract::getItemsCollection
Another approach that might be more suited would be to create the original block:
$productViewedBlock = $this->getLayout()->createBlock('reports/product_viewed');
On which you can simply call whatever you want:
$_collection = $productViewedBlock->getItemsCollection();
$_count = $productViewedBlock->getCount();
The getRecentlyViewedProducts function is a magical getter that gets the data that was set with setRecentlyViewedProducts in app/code/core/Mage/Reports/Block/Product/Viewed.php (which builds it using app/code/core/Mage/Reports/Block/Product/Abstract.php's function _getRecentProductsCollection).
This is complicated stuff that you don't want to reproduce; its better, IMO to make your own Block that extends Mage_Catalog_Block_Product_Abstract that will give you access to the same functionality, and drop your new block into the page you're working on.

MVC3: Repository Updates and ObjectStateManager

I have an Update method in my repository which I'm using to update articles on my project. I was initially using this method only to carry out admin edits for articles. It handles that correctly, but I decided I'd like to add a simple mechanism to calculate "most read" articles. In order to do that, I'd like to update TimesRead property each time an article has been viewed. This has been giving me trouble with the updates which seem to revolve around using ObjectStateManager.ChangeObjectState. Here's my Update method:
public void Update(Article article)
{
if (article == null) return;
db.Articles.Attach(article);
db.ObjectStateManager.ChangeObjectState(article, EntityState.Modified);
db.SaveChanges();
}
In my AdminController the following method updates correctly:
[HttpPost]
public ActionResult Edit(AdminEditViewModel viewModel)
{
if (ModelState.IsValid)
{
Article article = Mapper.Map<AdminEditViewModel, Article>(viewModel);
articleRepository.Update(article);
return RedirectToAction("Index");
}
viewModel.Categories = new SelectList(categoryRepository.GetAll(), "CategoryID", "Name", viewModel.CategoryID);
return View(viewModel);
}
However, in the TimesRead scenario, the update will trigger an exception of:
The object cannot be attached because it is already in the object context. An object can only be reattached when it is in an unchanged state.
Relevant code from that controller method:
var model = articleRepository.GetByID(id);
model.TimesRead++;
articleRepository.Update(model);
return View(model);
After having a look around to see what I can do to solve this, I came across the answer to this SO question. So I implemented that answer by replacing my Update method with the code suggested. This also works correctly in my admin scenario but not in the TimesRead scenario. The following exception is thrown:
An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.
The exceptions are quite clear in their meaning but it does leave me wondering how I am supposed to handle simple updates such as these. I found that I can "fool" the EF into thinking the model is unchanged by setting EntityState.Unchanged and that will update TimesRead but give an exception for admin updates, stating the ObjectStateManager doesn't hold a reference to the object.
It's also clear to me how these scenarios differ. The Edit action is mapping properties from a ViewModel onto a new, unattached Article object, whereas, ArticleController is dealing with an object retrieved directly from the context. That leaves me with the feeling I should refactor one of those controller methods so the steps taken to update are the same. I'm just not really sure how I should even approach that as both approaches seem like they should be able to coexist to me. So my question is, what can I change to get both types of update to work correctly?
Thanks for your time and I'm really sorry for the amount of code posted. I just feel it is all relevant to the problem.
The primary difference between your two methods is that the Admin Edit method creates a new Article from your AdminEditViewModel, then it attaches this newly created Article to your database. This works because it's a new object that has never been attached to a dc.
In the second case, you get an Article from the repository, update that Article, then try and attach it again, this fails because it's not a newly created Article, it's an Article returned from the db Context in the first place so it's already attached. and you are trying to attach it again.

ASP.NET MVC 2 - Set ViewData on every request in specific area (without inheritance)

In the "Admin" area of my application, an object must be available in ViewData on every page (for display in the Master template). I have already inherited from Controller, so I cannot make a simple base class that handles it. What is a good solution of doing this when not using inheritance? An ActionFilter seems interesting but I don't want to put it on every controller in the Admin area. I'm considering the following:
Custom ControllerFactory that detects Area as well
Application_BeginRequest(), though I have no knowledge on executing controller then.
Maybe you have a better solution?
In this case I would create a separate action that executes a partial view that shows the data you need. In my opinion this is the most clean solution for this kind of problem and it's easily testable and reusable.
i have a dropdown on my masterpage. you dont need viewdata for it. i did it like this
code on masterpage:
<%= Html.DropDownList("schselectr", MVC2_NASTEST.MvcApplication.masterSchooljaarList())%>
in Global.asax.cs
public static SelectList masterSchooljaarList() {
NASDataContext _db = new NASDataContext();
List<Schooljaar> newlist = _db.Schooljaars.ToList();
return new SelectList(_db.Schooljaars.ToList(), "Sch_Schooljaar", "Sch_Schooljaar");
}
so simply, it calls the method, which returns the data i need, every time you load the page. easy, clean, effective.