实体框架:将多个加载到一个实体 [英] Entity Framework: Loading Many to One entity

查看:118
本文介绍了实体框架:将多个加载到一个实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个角色实体和一个站点实体。现在,一个站点有很多角色,所以在Role类中有一个表示该关系的Site属性。如果我想要一个网站的角色,我会这样做:

  Site.Roles.Load()

问题是,由于Role类中的Site属性不是集合,只是一个实体,所以没有Load方法:

  currentRole.Site // ???? 

所以当一个角色被加载时,该网站是空的,没有办法得到该网站除了对角色集合的查询以获取SiteID,从站点集合获取站点,最后将其设置为currentRole的站点属性。



必须有更好的方法?我必须强制在查询中加入某种加入吗?看起来像这样的代码就像Load方法的行为一样生成。

解决方案

访问它将加载它。如果你希望它显式加载,对象查询应该有一个.Include()方法。

  db.Sites。包括( 角色)ToList()。 

这是一些文档


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.

解决方案

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

这篇关于实体框架:将多个加载到一个实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆