What is entity graph in Entity Framework? - entity-framework

I have been looking into some Entity framework tutorials and I have come across the word Entity Graph. I haven't got a clear idea about this term and its use. Can anyone provide info on this topic like what it is and its use in the context of entity framework?

When instantiated objects are joined together in a relationship they are referred to as
a graph, or an entity graph. The Entity Framework has some important rules about how
graphs are maintained.
Example, if you have a User(Entity) graph that consists of a User with Roles, Features.
When you detach the User
The User will be disconnected from this graph and the releationship references (Graph edges) will be destroyed.
You cannot travel from User to Roles/Features, because the graph edges (releationships) are destroyed.
I recommend you buy the "Programming Entity Framework DbContext" book (author: EF-Queen Julia Lerman) and you will find there a good explanation:
http://shop.oreilly.com/product/0636920022237.do

Google is your best friend here:
See this article for general definition and explanation of graphs
See here for specific information on EF and entity graphs

In Jpa hibernate fetching entities with associtions has always been a question for performance. Lazily loading associations with in a transaction again and again results in n+1 select issues and to avoid such issues JPQL join fetch and Criteria api joins are used. But fetching data with these two also result in Cross join issues means Cross join of all table records are returned to apllication by hibernate. Also altering fetch variable defined in annotaions on entity level is also not a good option for some cases. Hence to solve the above two issues entity graphs has been intoduced. All nodes defined in entity graphs are always eager fetched irrespective of their definition on entity level. These graphs are passed as a hint to queries . By passing graphs as a hint Cross join issues are solved as well as run time alteration of fetch behaviour can take place. For code you can check my github repository :
https://github.com/vaneetkataria/Jpa-Hibernate/blob/master/jdbcToJpaMigration/src/test/java/com/katariasoft/technologies/jpaHibernate/entity/fetch/entitygraph/dynamic/MultiInstructorsDynamicEntityGrpahTests.java

Related

What is the best practice for managing relationships using POST and PATCH in a RESTful API when the opposite entity already exists?

I am designing a RESTful API and my questions is the following: What is the best practice for managing relationships using POST and PATCH in a RESTful API? Where and when should I allow the consumer of the API to establish relationships between entities when the opposite entity/entities already exists/exist? My goals are to (a) minimize code and code maintenance with (b) a balanced ratio of easiness to understand the API and number of API calls to establish relationships. The most limiting criterion is that I am developing and maintaining the API on my own.
If it is of any interest, I am using ASP.NET Core and separated the API (with outer facing models) and the entity framework based data layer (with data models) into two different layers, where the API layer references the data layer (API -> Data).
I would like to discuss all possible combinations of the http request methods POST and PATCH and the three types of relationships one-to-one, one-to-many and many-to-many.
POST one-to-one
I was thinking about allowing the consumer of the API to let the POST request for the new entity only go through when the opposite entity has no relationship to any other entity of the posted entity type.
Another option would be to never allow setting relationships through POST but only let it update via PATCH. I favor this option, because it makes the entity easier and saver to create when treating the relationships separately. Even better, it would only require two API calls - one for POSTing the new entity and one for PATCHing even multiple relationships to many different one-to-one opposite entities.
POST one-to-many
One option would be allowing the consumer of the API to let the POST for the new entity only go through when all of the opposite entities have no relationship to any other entity of the posted entity type. Less save would be to allow the consumer to override existing relationships of the opposite entity to another entity of the type of the posted entity.
Another option would be to not allow posting any relationship of a single entity to many entities, because the relationships are effectively set in the opposite entities anyway. I prefer to only allow setting the relationship in the opposite entities via PATCH since this is the place where the many to one relationship is effectively established, and it keeps the creation of the entity separated from establishing relationships.
POST many-to-many
I would never allow to set a relationship for a POST request in a many-to-many relationship, but only allow to PATCH new relationships on both the new entity and the opposite entity. Due to the complexity of this type of relationship, I think it is best keep the entity creation as easy as possible and manage relationships separately through PATCH requests.
PATCH one-to-one
I would set no restrictions and allow the consumer of the API to set the relationship freely on both sides.
PATCH one-to-many
This one is a real dilemma for me - number of API calls vs easiness to understand relationships and lines of code.
On the one hand, I could allow to PATCH from the single entity point of view (it contains for example an array of opposite entity IDs). This would require only one API call to update the relationships of the multiple opposite entities, but this requires more code, because the data layer needs find and loop through all opposite entities. In addition, updating from the single entity point of view is sometimes hard to understand for me - many times its easier for me to establish the relationships in all opposite entities that refer to the same single entity.
On the other hand, I could allow the consumer of the API to update all opposite entities individually. This would require many API calls, but I sometimes think updating from this point of view is easier to understand, and the relationship is effectively set in the multiple opposite entities anyway.
I don't know what to favor yet. I am thinking about offering both options.
PATCH many-to-many
The only way I can see is to allow the consumer of the API to allow setting relationships on both sides due to the nature of this relationship.
While elaborating my ideas above, I think the best guideline is to keep creation of entities completely separated from establishing relationships and to set the relationships only where they are effectively established (mimicking SQL table behavior). I assume the latter one is what most API consumers should be familiar with and the first one keeps the API save and simple (at the cost of efficiency).
Please let me know if I missed any cases, criteria for decision making or didn't think of any implementation strategies.
Best regards,
philippfx

Perform join in core data

In my app I have two entities, User and Meetings. What I want is a list of User who have meetings today.
Also, I haven't added relationship between both the entities. Is there any way through which I can query both the entities in a single fetch request. Or is there any other way.
Please help me to solve this in best possible way
Thanks in advance
Core Data tries to map objects from the OOP-world into tables and rows from the rDBMS-world and back. This is called a object-relational mapper (ORM). Even this looks very easy, because concepts seems to be similar, it is a difficult task. One called it the "Vietnam of information technology".
However, at some point things do not go together. This is called the object-relational impedance mismatch (ORIM). At this point one has to decide, whether he takes the OOP-way or the rDBMS-way. Resolving relationships is one of this points.
Core Data decided to do this the OOP-way: Relationships are treated as relationships between "usual" objects. This has two consequences:
You do not join anything. In OOP objects are not joined. So in Core data objects are not joined. (However, they have some features in a fetch request with dictionaries, but this is not the usual way to access data in Core Data.)
To do the job, Core Data needs to know the relationships between objects. You have to set the relationships.

Entity Framework 5, Multiple Models, Same Entity

Ok, so I am new to entity framework...
I have an existing SQL database with some 500 tables in it, and we are in the process of considering a move from Linq->SQL to Entity Framework as our main data access layer. We also want to consider more of a domain driven design approach with separate data contexts managing key areas of the application ( i.e. Sales, Marketing, Jobs, Shipping etc. etc. ).
If we take a common entity such as "Customer", this appears in more than one model. I have two models in my sample app so far. Entity Framework is clever enough to create only one customer class ( we are using the default Poco T4 templates for class generation ), however when I try and run the project I get the following error "Multiple types with the name 'Customer' exist in the EdmItemCollection in different namespaces. Convention based mapping requires unique names without regard to namespace in the EdmItemCollection".
So am I right in thinking that Entity Framework does not allow "Customer" to exist in more than one model ? If I really want customer appearing in more than one model, do I have to start creating different versions of the customer class to deal with it ?
Apologies in advance if this is a dumb question, but I am relatively new to EF.
Thanks...
You said that you are creating DDD with bounded context. In bounded context, you create more than one context with one or more related entities in it. Why do you want to create more than one model with the same name?
Check the Julie Lerman's link for reference:
http://msdn.microsoft.com/en-us/magazine/jj883952.aspx
Sorry if I am out of context. But, in my experience in such a scenario, we have to create two different context such as "MarketingModelContext" and SalesModelContext. MarketingModelContext will have all the dbsets related to marketingmodel along with customer entity. In the same way, SalesModelContext will have all the dbsets related to SalesModel along with customer entity. In this way, you will be creating only one customer entity or POCO which can be used by two contexts independently. This is known as bounded contexts as Julie Lerman calls it. It will help you in separation of context, concerns and helps you with better performance as only required context(fewer entities) can be loaded. The above article will help you with this.
Hope I have answered your query.

How do I use entity framework with hierarchical data?

I'm working with a large hierarchical data set in sql server - modelled using the standard "EntityID, ParentID" kind of approach. There are about 25,000 nodes in the whole tree.
I often need to access subtrees of the tree, and then access related data that hangs off the nodes of the subtree. I built a data access layer a few years ago based on table-valued functions, using recursive queries to fetch an arbitrary subtree, given the root node of the subtree.
I'm thinking of using Entity Framework, but I can't see how to query hierarchical data like
this. AFAIK there is no recursive querying in Linq, and I can't expose a TVF in my entity data model.
Is the only solution to keep using stored procs? Has anyone else solved this?
Clarification: By 25,000 nodes in the tree I'm referring to the size of the hierarchical dataset, not to anything to do with objects or the Entity Framework.
It may the best to use a pattern called "Nested Set", which allows you to get an arbitrary subtree within one query. This is especially useful if the nodes aren't manipulated very often: Managing hierarchical data in MySQL.
In a perfect world the entity framework would provide possibilities to save and query data using this data pattern.
Everything IS possible with Entity Framework but you have to hack and slash your way in to it. The database I am currently working against has too many "holder tables" since Points for instance is shared with both teams and users. Both users and teams can also have a blog.
When you say 25 000 nodes do you mean navigational properties? If so I think it could be tricky to get the data access in place. It's not hard to navigate, search etc with entity framework but I tend to model on paper then create the database based on how I want to navigate while using entity framework. Sounds like you don't have that option.
Thanks for these suggestions.
I'm beginning to realise that the answer is to remodel the data in the database - either along the lines of nested sets as Georg suggests, or maybe a transitive closure table, which I've just come across.
That way, I'm hoping to get two key benefits:
a) faster querying aginst arbitrary subtrees
b) a data model which no longer requires recursive querying - so perhaps bringing it within easy reach of the Entity Framework!
It's always amazing how so often the right answer to a difficult problem is not to answer it, but to do something else instead!

How to do the opposite of eager-loading in Entity Framework?

I understand in Entity Framework you can specify relationships that need to be joined with Include:
Product firstProduct =
db.Product.Include("OrderDetail").Include("Supplier").First();
But we have the opposite issue that a simple LINQ statement is getting making too many JOINs on the SQL server.
So how do we do the opposite, i.e. tell Entity to not do any deep loading of joined tables when it gets all the orders, so that on the SQL Server it executes:
SELECT * FROM Orders
The Entity Framework often goes ahead and loads basic relationship information too.
It does this so users can make updates easily, without violating the EF's unique concurrency policy for relationships.
You can turn this off however by doing a no tracking query.
See Tip 11 - How to avoid relationship span for more information for more information
Alex