实体框架 - 如何使用实体关联?

时间:2023-01-27 15:18:39

When I have tables in my database that have PK/FK relationships (int) and when they are modeled by the Entity Framework designer everything seems as it should be. I can write the code below and everything seems like it's going to work fine as well but then when I run the code I get an error on the project.Status.StatusName saying the Object reference not set to an instance of an object. I guess I was under the impression that the framework populated the associated entities when you populate the parent entity.

当我的数据库中的表具有PK / FK关系(int)时,当它们由实体框架设计器建模时,一切都应该如此。我可以编写下面的代码,一切看起来它也可以正常工作但是当我运行代码时,我在项目上得到一个错误.Status.StatusName说Object引用没有设置为对象的实例。我想我的印象是,当您填充父实体时,框架会填充关联的实体。

    Dim db As New MyDbModel.MyDbEntities()

    Dim project As MyDbModel.Project = (From p In db.Project Where p.ProjectID = 1).First

    Response.Write(project.ProjectName)        
    Response.Write(project.Status.StatusName)

2 个解决方案

#1


Try using Include(RelationshipName)

尝试使用Include(RelationshipName)

Dim db As New MyDbModel.MyDbEntities()    
Dim project As MyDbModel.Project = (From p In db.Project.Include("Status") Where p.ProjectID = 1).First    
Response.Write(project.ProjectName)            
Response.Write(project.Status.StatusName)

#2


Entity Framework does not load related entities unless you tell it to. In order to access related entities you need to either Load() them explicitly or use Include(). Here's a short sample.

除非您告知,否则实体框架不会加载相关实体。要访问相关实体,您需要显式加载()或使用Include()。这是一个简短的样本。

http://blogs.msdn.com/bethmassi/archive/2008/12/10/master-details-with-entity-framework-explicit-load.aspx

#1


Try using Include(RelationshipName)

尝试使用Include(RelationshipName)

Dim db As New MyDbModel.MyDbEntities()    
Dim project As MyDbModel.Project = (From p In db.Project.Include("Status") Where p.ProjectID = 1).First    
Response.Write(project.ProjectName)            
Response.Write(project.Status.StatusName)

#2


Entity Framework does not load related entities unless you tell it to. In order to access related entities you need to either Load() them explicitly or use Include(). Here's a short sample.

除非您告知,否则实体框架不会加载相关实体。要访问相关实体,您需要显式加载()或使用Include()。这是一个简短的样本。

http://blogs.msdn.com/bethmassi/archive/2008/12/10/master-details-with-entity-framework-explicit-load.aspx