实体框架-如何在扩展类中使用实体关系? [英] Entity Framework - how do I use the entity relationships in my extended classes?
问题描述
我正在尝试扩展实体框架创建的部分类,以便我可以更轻松地使用下面的代码中的对象(请让我知道是否有更好或更例外的方法可以使用实体框架进行此操作)
I am trying to extend the partial classes that the entity framework creates so that I can more easily work with objects like in the code below (please let me know if there's a better or more exceptable way of doing this with the entity framework)
Public Sub New(ByVal ProjectID As Integer)
Dim proj As Project = (From p In db.Project.Include("Status") Where p.ProjectID = ProjectID).First
_ProjectID = proj.ProjectID
_ProjectName = proj.ProjectName
Me.Status.StatusID = proj.Status.StatusID 'I get errors here
Me.Status.StatusName = proj.Status.StatusName 'and here
End Sub
但是,我当然会在线上看到对象引用未设置为对象的实例":Me.Status.StatusID = proj.Status.StatusID
But of course I get the "Object reference not set to an instance of an object" on the line: Me.Status.StatusID = proj.Status.StatusID
扩展部分类时如何传递相关的实体值?还是我只是离开这里而已,而在这里做我想做的事情有更简单的方法吗?
How can I pass through the related entity values when extending the partial classes? Or am I just way off base here and there's a much easier way of doing what I'm trying to do here?
推荐答案
似乎您试图基于构造函数的ID加载对象
It seems like your trying to load the object based on the id from the construtor
我个人不会使用构造函数来加载对象,您可以使用共享函数,也可以在代码中直接使用LINQ来加载对象.
I personally wouldn't use the constructor to load the object, you can either use a shared function or use LINQ directly in your code to load your object.
使用类似
Public Shared Function GetProjectById(ByVal ProjectId as Integer) as Project
Dim db As New MyDataContext
Return (From p In db.Project.Include("Status") Where p.ProjectID = ProjectID).FirstOrDefault
End Function
这篇关于实体框架-如何在扩展类中使用实体关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!