Updating many-to-many relations in JayData - many-to-many

My OData model contains a pair of entities with many-to-many relationship (Parents-Children). I am trying to add a child entity to a parent's Children navigation property, but calling saveChanges() afterwards has no effect at all. The code looks something like:
// both 'parent' and 'child' are attached to the context
// both have their navigation properties empty
parent.Children.push(child);
context.saveChanges();
I have also tried:
parent.Children = parent.Children.concat([child]);
parent.Children = [child];
But to no avail, it still doesn't work - the saveChanges() call doesn't make any requests to the service, as if there is nothing to update.
I'd really appreciate an example of how to work with many-to-many relations using JayData, and some help dealing with the issue described above.
Thanks

Related

Self referencing loop Detected for property in Asp.net MVC with Angular 2

I Have Create a DB in that I am Having Multiple tables having Relationship between them.
When a try to get data from my WEb app i get this error
"'Self referencing loop detected with type 'System.Data.Entity.DynamicProxies.PrescriptionMaster_2C4C63F6E22DFF8E29DCAC8D06EBAE038831B58747056064834E80E41B5C4E4A'. Path '[0].Patient.PrescriptionMasters"
I coudn't get why i am getting this error, and when i remove the relationships between tables i get proper data From it.
I have Tried other solutions like adding
"config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling
= Newtonsoft.Json.ReferenceLoopHandling.Ignore; "
in Webconfig.cs but nothing has worked for me.
Please help me, what should I do ?
The only proper way to prevent this from happening is by not sending Entity Framework objects (which may contain such loops) into the JSON Serializer (which is not too good at knowing when to stop serializing).
Instead, create ViewModels that mimic the parts of the EF Objects that your Front End actually needs, then fill those ViewModels using the EF Objects.
A quick-and-dirty way is to just use anonymous objects, for example:
return new
{
Product = new
{
Id = EF_Product.Id,
Name = EF_Product.Name
}
};
A good rule-of-thumb is to only assign simple properties (number, bool, string, datetime) from the EF Objects to the ViewModel items. As soon as you encounter an EF Object property that is yet another EF Object (or a collection of EF Objects), then you need to translate those as well to 'simple' objects that are not linked to EF.
On the other end of the spectrum there are libraries such as AutoMapper. If you decide that you need actual ViewModel classes, then AutoMapper will help mapping the EF Objects to those ViewModels in a very structured way.
Just add this to the Application_Start in Global.asax:
HttpConfiguration config = GlobalConfiguration.Configuration;
config.Formatters.JsonFormatter
.SerializerSettings
.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
It will ignore the reference pointing back to the object.

Grabbing associationType in Sequelize

I was reading the Sequelize documentation and I am trying to figure out how to get the associationType of a model. It seems like you should be able to import a model (e.g. Posts) and call Posts.associationType or Posts.association.associationType. Docs on Associations
I also found an old stack overflow question which mentioned that calling something like Posts instanceof sequelize.Association.BelongsTo should work as well. When I call Posts.associations it only gives me the association as a key and value. {'Comments': 'Comments}
But neither method works. I seem to be able to access the rest of the model's attributes perfectly fine.
You are only seeing the toString() version of the output. It is more clear if you try:
console.log(Object.keys(models.Posts.associations));
This will give you an array of the keys of the associations, so you can use them to access more details:
console.log(Object.keys(models.Posts.associations.Comments));
You will then see that it has an associationType property which you can use to get the string value you are looking for. Comments is the name/key for the association which can be overridden with the as attribute in the definition.
// type = "BelongsTo"
var type = models.Posts.associations.Comments.associationType;

MVC3 and EF: How to handle CRUD operations of nested entities (Parent, Child and Grandchild)

I'm new to MVC 3 and Entity Framework so I'd like to know what is the best approach.
Basically, I have 3 entities: Course, Module and Chapter. Each is a parent of the next with a one to many relationship (A Course has many Modules and a Module has many Chapters). I have a column SortOrder for Modules and Chapters to have them ordered sequentially.
My idea was is to use partial views for the child entities when updating the parent.
I have 3 views in mind:
Create/Update Course: all basic details for a course
Course Modules (basically a different view for Update Course) which has an option to add multiple partial views, each creating a Module
Course Timeline (still a different view for update course) which lists all Modules (on separate divs) and has the option to add multiple partial views, each creating a Chapter
Does my plan sound right and plausible? I plan to use hidden fields to store IDs. I also want the saves to occur asynchronously.
Any piece of advise or information would be highly appreciated. Thanks!
I think this is what your after but not sure. For handling persistence of child/grandchild entities, you can do this in several ways. You can either perform crud operations on each entity separately. So that will involve for example saving the modules by themselves with a reference to the course, probably courseId.
Or you can look at saving just the aggregate root, which in this case looks like its your Course entity. This will involve Loading the course, populating the modules on the course, and for each module populate the chapters. Then when you `db.Courses.Add(newCourse); db.SaveChanges(); all the entities will be persisted. You have to make sure your foreign key and model references are setup correctly.
For example, to save child entities:
public ActionResult DoSomething(int courseId, Module newModule)
{
var course = someService.LoadCourse(courseId);
course.Modules.Add(newModule);
using (var db = new MyDbContext())
{
db.Courses.Add(course);
db.SaveChanges();
}
return RedirectToAction("Success");
}
Or you can save individually:
public ActionResult DoSomething(Module newModule)
{
using (var db = new MyDbContext())
{
//You will need to make sure newModule.CourseId is set correctly
db.Modules.Add(newModule);
db.SaveChanges();
}
return RedirectToAction("Success");
}
Depending on your views, you will be able to judge which way is best to go. Regarding asynchronous saving, you will be able to call these endpoints with jquery posting the models as json. On a side note, one thing to look at would be to create a custom Anti Forgery Token validator for json requests, example.

Guidance for synchronising reverse associations in Entity Framework 4.1

EF 4.1 synchronises reverse associations when you create your instances. Is there any documentation of or best practices guidance available for this behaviour?
What I mean by synchronising the reverse association is that given:
public class Blog
{
public Blog() { Posts = new List<Blog>(); }
public int Id { get; set; }
public ICollection<Post> Posts { get; private set; }
}
public class Post
{
public Blog Blog { get; set; }
public int Id { get; set; }
}
Then after the following line the Post will have it's Blog property set.
var blog = new Blog();
context.Blogs.Add(blog);
blog.Posts.Add(new Post());
I believe - but I'm not sure - with "synchronising the reverse association" you mean a feature in Entity Framework which is called Relationship Fix-up or Relationship Span and is responsible to assign automatically navigation properties between objects in the ObjectContext. This is not specific to EF 4.1 but exists also for older versions.
I don't know a comprehensive documentation for this feature but here are a few resources which may give a bit more insight - especially the second one:
A brief definition: http://blogs.msdn.com/b/alexj/archive/2009/04/03/tip-10-understanding-entity-framework-jargon.aspx
A more detailed explanation (Zeeshan Hirani): http://www.daltinkurt.com/upload/dosyalar/file/Diger/entity_framework_learning_guide.pdf (Chapter 3.4 at page 125 - 133)
About situations where one wants to avoid relationship span: http://blogs.msdn.com/b/alexj/archive/2009/04/07/tip-11-avoiding-relationship-span.aspx
Edit
I am not able to give a comprehensive explanation of relationship span and all its impacts. But I can try to give a few examples where I feel safe that it's not completely wrong what I say:
In the answer you have linked in the comment Morteza makes a difference between entities which are derived from EntityObject (only ObjectContext in EF 4.0, not possible with DbContext in EF 4.1) and POCOs (possible with ObjectContext and DbContext).
If you have POCOs then adding a new object to a navigation collection of another object which is already loaded into the context would not attach the new object to the context. This is not surprising because POCOs are, well..., POCOs, which means that they don't know anything about the EF context. Adding an object to a navigation collection is really nothing more than something like List<T>.Add(...). This generic Add method doesn't do any operation on the EF context.
This is another situation with EntityObject and EntityCollection which both have references to the context internally and can therefore attach to the context immediately when you add to the collection.
One conclusion from this consideration is that the last code example in your question would not actually set the Blog property in the Post when you use POCOs. But: It will be set after you have called DetectChanges or SaveChanges (which calls DetectChanges internally). In this situation DetectChanges (which is probably a very complex method) looks into context what objects are there (it'll find the Blog parent object) and then runs through the whole object graph (the Posts collection in our case) and checks if the other objects in the graph (the Post objects) are also in the context. If not - and this is the case in your example - it will attach them to the context in Added state and - here comes relationship span into play now - also fix the navigation properties in the object graph.
Another situation where relationship span also acts with POCOs is when you load objects into the context.
For example: If you have a Blog with id = x and a Post with id = y which belongs to this Blog in the database then this code ...
var blog = context.Blogs.Find(x); // no eager loading of the Posts collection!
var post = context.Posts.Find(y); // no eager loading of the Blog property!
would automatically build up the navigation properties in each object, so the Posts collection of the Blog will suddenly contain the post and the Blog property in Post will refer to the blog. This relationship fix-up depends on the fact that the objects are indeed loaded into the context. If you suppress this by using AsNoTracking for example ...
var blog = context.Blogs.AsNoTracking().Where(b => b.Id == x).Single();
var post = context.Posts.AsNoTracking().Where(p => p.Id == y).Single();
... relationship span doesn't work and the navigation properties will stay null.
A last note: Relationship span - as in the example above - only works if the assocation on at least one end has a cardinality of 0...1 (one-to-one or one-to-many associations). It never works for many-to-many associations. This was recently discussed here (with EF 4.1): EF 4.1 loading filtered child collections not working for many-to-many

Cant convert poco object from EF 4 to JSON

Im working on a mvc 2.0 application using the entity framework. With the entityframework I use the repository pattern with poco objects. To start off with the issue, when I convert an entity object to json I get a circular reference error.
After some search I discovered that there are proxy's generated to support lazy loading. If there are navigation properties between two classes (A and B), this results in a circurar reference error. Quite understandable. So I try to work around it.
I disabled the proxies and the lazy loading. This works if I only want to load Class A. Instead of the proxy's there are now null values, so they can be parsed.
But now I want to load a class, for instance Orders and I want to see what customer placed the order:
Suppose I have class Customer that has a navigation property to Order (1 to more) and Order has a reversed navigation property to Customer. When I turn the proxys off, I get a nice json back with all the orders, but not with the Customers. When I turn the proxies on, I get a circular error.
But how could I get back the orders, with the customer that bought them. Is it possible to create a linq that retreives the orders and load the customers (I have a repository for both customers and orders)? Or is there a way to strip off the proxy-objects?
I hope my post is clear enoug and someone can help me.
Problem:
Right. So you have the relationship A -> B with B being the many side.
in the EF model A gets a navigation property B and B gets a navigation property A.
Circular reference... great...
Solution:
In your model, rightclick on the B's navigation property A and choose properties.
Getter and setter there should both be public initially. Set the getter to Private.
Now something like this should work.
var results = from a in ctx.A.Include("B")
select a;
var list = results.ToList(); //This is important otherwise youll get a error that the context has been disposed on the next line.
return Json(list, JsonRequestBehavior.AllowGet);
Hope this helps.
PS:
After reading my answer after posting it, I'm not so sure anymore that I'm really answering your question, sorry. Ill leave it up nonetheless.