众所周知,如果实体已加载,则无法直接在 Linq to SQL 中设置外键 ID。但是,您可以通过外键查找实体,然后使用实体关系将实体设置为外部实体。 (为了简单起见,我在这里取出了枚举并使用整数值)。即,如果我有一个已加载的约会实体和关联的 AppoinmentStatus 实体,我无法执行此操作:-
ExistingAppointment.AppointmentStatusID = 7
但我可以这样做:-
ExistingAppointment.AppointmentStatus = (From appstat In db.AppointmentStatus _
Where appstat.StatusID = 7 _
Select appstat).Single
我的代码中有这种东西,我想重构。所以...
我显然可以在这样的模块中使用辅助方法:-
Module Helper
Public Shared Function GetAppointmentStatus(ByVal AppStatusID As Integer) As AppointmentStatus
GetAppointmentStatus = (From appstat In db.AppointmentStatus _
Where appstat.AppointmentStatusID = AppStatus _
Select appstat).Single
End Function
End Module
我什至可以将其变成扩展方法,就像这样。
Imports System.Runtime.CompilerServices
Module Helper
Extension()> _
Public Shared Function GetAppointmentStatus(ByVal db as DataClassesDataContext, ByVal AppStatusID As Integer) As AppointmentStatus
GetAppointmentStatus = (From appstat In db.AppointmentStatus _
Where appstat.AppointmentStatusID = AppStatusID _
Select appstat).Single
End Function
End Module
我还可以将其放入 Linq to SQL 部分类中,如下所示。
Partial Public Class DataClassesDataContext
Public Function GetAppointmentStatus(ByVal AppStatusID As Integer) As AppointmentStatus
GetAppointmentStatus = (From appstat In Me.AppointmentStatus _
Where appstat.AppointmentStatusID = AppStatusID _
Select appstat).Single
End Function
End Class
此外,我可以将代码放入 Linq to SQL Appointment Entity 部分类中,如下所示:-
Partial Public Class Appointment
Public Function GetAppointmentStatus(ByVal db as DataClassesDataContext, ByVal AppStatusID As Integer) As AppointmentStatus
GetAppointmentStatus = (From appstat In db.AppointmentStatus _
Where appstat.AppointmentStatusID = AppStatusID _
Select appstat).Single
End Function
End Class
我应该做什么,为什么,或者有更好的选择吗?