Entity Framework: Loading Many to One entity

2019-05-18 17:59发布

问题:

Say I have a role entity and a site entity. Now there are many roles to one site, so on the Role class there is a Site property that represents that relationship. If I wanted the roles for a site I would do this:

Site.Roles.Load()

Problems is, since the Site property on the Role class isn't a collection but just a single entity, there is no Load method:

currentRole.Site //????

So that when a role is loaded, the Site is null and there is no way to get the site other than say a query on the role collection to get the SiteID, getting the Site from the site collection, and finally setting that to currentRole's site property.

There has to be a better way? Do I have to force some kind of join in the query? Seems like this would be generated by code just like the Load method behaves.

回答1:

Accessing it will load it. If you want it to load it explicitly there should be an .Include() method on the object query.

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

Here's some documentation



回答2:

Actually, accessing it will not automatically load it. You can include the related entity in a single query using the Include method, but you can also use a Load method with references just like you can with collections--it's just not on the CLR reference property but on an EntityReference property parallel to the CLR reference on the entity. It's name is the same as the CLR reference but with the word "reference" tacked on. So you can say:

currentRole.SiteReference.Load();

For what it's worth, in the VS 2010 / .net 4.0 release of the EF, it will also be possible to set a property on the ObjectContext which will turn on implicit lazy loading so that accessing the clr reference will automatically just load it if it hasn't been loaded already.

Danny