Entity Framework: loading from several to one object

Let's say that I have a role object and a site object. Now there are many roles on one site, so the Role class has a Site property that represents this relationship. If I wanted roles for the site, I would do this:

Site.Roles.Load()

The problem is that the Site property in the Role class is not a collection, but just a single object, there is no Load method:

currentRole.Site //????

Thus, when the role is loaded, the site is zero, and there is no way to get the site, except to say a request in the role collection to get the SiteID, get the site from the site collection, and finally establish what the current site resource is.

Should there be a better way? Should I force some kind of connection in the request? It looks like this will be generated by the code in the same way as the Load method.

+2
source share
2 answers

Access to it will be downloaded. If you want it to explicitly load it, the object request must have a .Include () method.

db.Sites.Include("Role").ToList();

Here is some documentation

+1
source

In fact, accessing it will not automatically download it. You can include a linked object in a single query using the Include method, but you can also use the Load method with links in the same way as with collections - it’s just not for the CLR link property, but for the EntityReference property parallel to the CLR object link. This name matches the CLR link, but the word link. Therefore you can say:

currentRole.SiteReference.Load();

, , EF VS 2010/.net 4.0, ObjectContext, , clr .

+6

Source: https://habr.com/ru/post/1704850/


All Articles