Entity Framework - how do I use the entity relationships in my extended classes?

青春壹個敷衍的年華 提交于 2019-12-11 07:38:50

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!