问题
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
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?
回答1:
It seems like your trying to load the object based on the id from the construtor
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.
use something like
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
来源:https://stackoverflow.com/questions/384138/entity-framework-how-do-i-use-the-entity-relationships-in-my-extended-classes