使用 linq 和 EF 创建对象,而不定义其字段



我有一个简单的方法,用于通过customerId从数据库中获取客户:

Public Function GetCustomer(ByVal id As Long) As Customer
        Using ctx As New MyEntities
            Dim e = (From c In ctx.customers
                    Join bp In ctx.billingpoints
                    On c.customerId Equals bp.customerId
                    Select New Customer With {
                        .customerId = c.customerId
                        .billingPoint = New BillingPoint With{
                                            .customerId = bp.customerId
                                            .billingPointId = bp.billingPointId
                                            'tons of more fields   
                                        }
                        'tons of more fields
                           })
        Return e
    End Using
End Function

此方法返回如下所示定义的 Customer 对象:

Public Class Customer
    Public Property customerId As Long
    Public Property billingPoint As BillingPoint
    'many more fields
End Class

如您所见,设置了所有属性后,这看起来很可怕。有没有更有效的方法呢?

我假设您是在问,因为您的对象模型不包含客户对象上 BillingPoint 类型的显式映射关系属性,而只是通过 BillingPoint 上的 customerId 属性在两个实体之间隐式关系。

如果要保持模型的样式(在许多情况下可能有效),则可以考虑将查询结果映射到 CustomerDTO 类型。这可以使用自动映射器及其可查询扩展自动完成:

https://github.com/AutoMapper/AutoMapper/wiki/Queryable-Extensions

您可以使用实体框架已经生成的类,而无需使用属性重新创建类型,除非您需要特定类型的模型,否则您必须手动执行映射,或者编写一个泛型扩展,通过"Name"

最新更新