Latest Posts

Ef core include multiple grandchildren

EF can map a. NET type hierarchy to a database. This allows you to write your. NET entities in code as usual, using base and derived types, and have EF seamlessly create the appropriate database schema, issue queries, etc. The actual details of how a type hierarchy is mapped are provider-dependent; this page describes inheritance support in the context of a relational database.

TPH uses a single table to store the data for all types in the hierarchy, and a discriminator column is used to identify which type each row represents. By convention, EF will only set up inheritance if two or more inherited types are explicitly included in the model. EF will not automatically scan for base or derived types that are not otherwise included in the model.

You can include types in the model by exposing a DbSet for each type in the inheritance hierarchy:. This model be mapped to the following database schema note the implicitly-created Discriminator column, which identifies which type of Blog is stored in each row :.

Database columns are automatically made nullable as necessary when using TPH mapping. For example, the RssUrl column is nullable because regular Blog instances do not have that property. If you don't want to expose a DbSet for one or more entities in the hierarchy, you can also use the Fluent API to ensure they are included in the model. If you don't rely on conventions, you can specify the base type explicitly using HasBaseType.

You can also use. HasBaseType Type null to remove an entity type from the hierarchy. You can configure the name and type of the discriminator column and the values that are used to identify each type in the hierarchy:. In the examples above, EF added the discriminator implicitly as a shadow property on the base entity of the hierarchy. This property can be configured like any other:. By default, when two sibling entity types in the hierarchy have a property with the same name, they will be mapped to two separate columns.

However, if their type is identical they can be mapped to the same database column:.

ef core include multiple grandchildren

You may also leave feedback directly on GitHub. Skip to main content. Exit focus mode. Note Database columns are automatically made nullable as necessary when using TPH mapping. Tip If you don't rely on conventions, you can specify the base type explicitly using HasBaseType. Is this page helpful? Yes No. Any additional feedback? Skip Submit. Send feedback about This product This page. This page. Submit feedback. There are no open issues. View on GitHub.NET Framework is 4.

NET is 6. I have looked on here for my answer but everything that I have tried or that was mentioned is not available to me. I have the following code to acquire grandchildren of children of a particular parent right now, I know there has to be a more efficient way of acquiring those grandchildren but cannot figure out how:. I have tried using. ThenInclude and Include "xxxx. ThenInclude is not even available to me and the Include "xxxx. The Include only allows me to enter a string path and yet I have seen comments that the OP was using an older version of EF.

However, this will replace the current parents. Count number of SQL queries with single, but monster SQL query consolidating all the columns and all the records in a single result set, which may not be efficient as well. I would suggest you a hybrid approach similar to the way EF Core processes the Include s which will execute 1 SQL per parents, 1 per children and 1 per each grandchildren typei. Only the parent query result is stored into variable, the children and grandchildren queries are just executed, and the whole dirty work is done by EF navigation property fix-up:.

Returning multiple grandchildren of child of parent from Entity Framework. Include "scheduledetails" where a.

Entity Framework Core with multiple DB Contexts, Schemas and Projects

I am stuck on this, can I be enlightened on if I am missing something here? Bulk Delete. Bulk Update. Bulk Merge. Accepted Answer You can chain multiple Include "xxxx. Load ; childQuery. Ivan Stoev. View more on Stack Overflow. Prime Library. Not affiliated with Stack Overflow.

ef core include multiple grandchildren

SaveChanges vs BulkSaveChanges. Try for free now.Sometimes database schema can get complex and large, in such cases, database schema is usually separated in multiple schemas where one team can be responsible for subset of the DB schemas and back-end code accessing the schemas. Entity framework core v2. I named the entry project and solution MultipleDbContexts. A number of nuget packages needs to be referenced. After referencing all packages, MultipleDbContexts.

ValuesController is added by the template and we will leave it as it is for now. Same for Startup. Create a new empty database and name it multipleDbContexts. In order to use the database, we need to add connection string to appsettings.

Users project will have UsersDbContext which will reference tables Users. User and Users. Add new class library to the solution and reference it in entry project.

Eager Loading child entities in Entity Framework

Users class library needs to reference EF nugets, so after adding all needed packages, MultipleDbContexts. Now we need to create MultipleDbContexts. Products class library and reference same nuget packages, and set reference from the entry project to the MultipleDbContexts. It's time to add table models to MultipleDbContexts. Products and MultipleDbContexts.

For migrations to work, we need to specify entry project when using dotnet ef command. That is done with -s argument. We also need to specify for which context we are applying migration, which is done with --context argument. Open command prompt in directory where MultipleDbContexts. Products is located and enter the following commands:. Similar commands are needed for MultipleDbContexts. Users in the directory of the project. Now our DB should have tables.Entity Framework code first creates tables for each concrete domain class.

You can also design your domain classes using inheritance. TPH inheritance uses one database table to maintain data for all of the entity types in an inheritance hierarchy. Here is the very simple model which contains one abstract class Person and two non-abstract classes Student and Teacher. Student and Teacher classes inherit the Person class. If you don't want to expose a DbSet for one or more entities in the hierarchy, you can use the Fluent API to ensure they are included in the model.

And if you don't rely on conventions, you can specify the base type explicitly using HasBaseType. Now to create a database using migrations from your model, run the following two command in Package Manager Console.

Loading Related Data

As you can see in the DB schema, Code First has added all the properties in one table and also added a discriminator column to distinguish between persistent classes. TPH has one major problem, Columns for properties declared by subclasses will be nullable in the database. For more information see Inheritance Relational Database. Bulk Delete. Bulk Update. Bulk Merge. Prime Library.By using our site, you acknowledge that you have read and understand our Cookie PolicyPrivacy Policyand our Terms of Service.

The dark mode beta is finally here. Change your preferences any time. Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information. One can include children and grandchildren using Lambda syntax using System. Entity like this:.

The Lambda syntax prevents breaking the query if the class names are subsequently altered. Is the string syntax the only option, or is there some alternative way to use Lambda syntax in this situation?

Update: If you are using Entity Framework Core you should use the following syntax. Learn more. Asked 7 years, 2 months ago.

Migrating EDMX projects to Entity Framework Core

Active 2 years, 9 months ago. Viewed 8k times. Include "Children. GrandChild" select p; Is the string syntax the only option, or is there some alternative way to use Lambda syntax in this situation? Eric J.

Active Oldest Votes.

ef core include multiple grandchildren

Gert Arnold Gert Arnold To use the include method like this don't forget to reference System. You can recursively continue this Select pattern for descendants as well if the grandchild has children and so on. GrandChild select p. Note: In my case, for some weird reason intellisense wouldn't prompt me with the Grandchild object in the ".

ThenInclude" lambda clause, but this was an edge case where intellisense was wrong and it didn't matter - the code still compiled. Julen you can use. ThenInclude recursively for every nested child entity, like this: Parent. Include child. ThenInclude GrandChild. ThenInclude GrandGrandChild. How would you include two different grandchildren, say GrandSon and GrandDaughter?NET functions in the query. This was not possible in EF 6. This will execute the following query in the database:.

Entity Framework Core supports eager loading of related entities, same as EF 6, using the Include extension method and projection query. In addition to this, it also provides the ThenInclude extension method to load multiple levels of related entities. EF 6 does not support the ThenInclude method. Unlike EF 6, we can specify a lambda expression as a parameter in the Include method to specify a navigation property as shown below.

In the above example. Grade to specify a reference property to be loaded with Student entity data from the database in a single SQL query. The above query executes the following SQL query in the database.

ef core include multiple grandchildren

We can also specify property name as a string in the Include method, same as in EF 6. The example above is not recommended because it will throw a runtime exception if a property name is misspelled or does not exist.

Always use the Include method with a lambda expression, so that the error can be detected during compile time. The Include extension method can also be used after the FromSql method, as shown below.

Note: The Include extension method cannot be used after the DbSet. Find method. Find 1. Include is not possible in EF Core 2. This may be possible in future versions. Use the Include method multiple times to load multiple navigation properties of the same entity. For example, the following code loads Grade and StudentCourses related entities of Student. EF Core introduced the new ThenInclude extension method to load multiple levels of related entities. Consider the following example:.Everything has many way to do it, here is two ways to handle data structure that is recursive.

The structure in which the solution that I will present you work is a structure that look like a tree. Also, children cannot contain parent that are already used somewhere in the tree, which could raise additional problems, like having infinite recursion. In the graphic above, you can see that we have two types of container. One is green and the other one is having a white background. In fact, the green container is a node that can have either children of a specify entity which cannot contain any other structural entity or can contain an other green container which are those who contain a list of children.

This give us the option to load the Children, if this one has children then load it the way we just load the parent since every child become a parent. This require recursive method. The problem is that it work but every load will create a new parent. We need to map every values to the first parent to have at the end a single hierarchical tree. Here is how we can do it with eager loading. We need to every property set back to the object that we have receive to, at the end, have a tree fully loaded.

But, we can do better with explicit loading. One of the positive characteristic of explicit loading is that it load itself. This has the advantage to remove every mapping since the object is loaded itself by entity framework. Still, this kind of loading come with a price. If we have 40 leafs in the tree, this mean that every of them will be loaded by the database which result to 40 SQL queries. One approach that can reduce the amount of request is to have the ID int or Guid inside the object, from there you can check if this one has a value.

This will reduce the amount of call to the database at the amount of parent only not final leaf which return 0 element. Still, the amount is huge and for large application, a custom solution with a view returning a bunch of data and parsed manually may be a good solution.

Nevertheless, if you need to save the tree, you could end up with problem which you do not have when having the whole structure loaded by Entity Framework. If you like my article, think to buy my annual book, professionally edited by a proofreader. Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed. As of the date ofPatrick Desjardins has been employee by Netflix. Before, from toemployee by Microsoft Corporation. The views expressed in this blog are those of the author, Mr. Desjardins, and do not necessarily reflect those of Netflix or Microsoft Corporation. Microsoft Techno ASP. Net ASP. Yves Vaillancourt says:.

October 2, at Patrick Desjardins says:. October 4, at


Leave a Reply

Your email address will not be published. Required fields are marked *