LINQ-to-SQL 通用 GetByIDs 方法

发布于 2024-11-07 03:23:01 字数 775 浏览 6 评论 0原文

我目前正在使用它通过主键值获取对象。

我正在尝试找到一种方法来创建类似的方法 GetByIDs,其中我可以传递 IEnumerable(of object) 并执行 ids.contains(pk),但没有 Contains 表达式。

有人知道我会怎么做吗?

Public Function GetByID(Of T As Class)(ByVal pk As Object) As T
    Dim itemParam = Expression.Parameter(GetType(T), "item")
    Return GetTable(Of T).Single(
        Expression.Lambda(Of Func(Of T, Boolean))(
            Expression.Equal(
                Expression.Property(itemParam, GetPrimaryKeyName(Of T)),
                Expression.Constant(pk)
                ),
            New ParameterExpression() {itemParam}
            )
        )
End Function

Public Function GetPrimaryKeyName(Of T)() As String
    Return Mapping.GetTable(GetType(T)).RowType.IdentityMembers(0).Name
End Function

I'm currently using this to get an object by it's primary key value.

I'm trying to find a way to create a similar method GetByIDs where I can pass an IEnumerable(of object) and do ids.contains(pk), but there's no Contains expression.

Anyone know how I would do this?

Public Function GetByID(Of T As Class)(ByVal pk As Object) As T
    Dim itemParam = Expression.Parameter(GetType(T), "item")
    Return GetTable(Of T).Single(
        Expression.Lambda(Of Func(Of T, Boolean))(
            Expression.Equal(
                Expression.Property(itemParam, GetPrimaryKeyName(Of T)),
                Expression.Constant(pk)
                ),
            New ParameterExpression() {itemParam}
            )
        )
End Function

Public Function GetPrimaryKeyName(Of T)() As String
    Return Mapping.GetTable(GetType(T)).RowType.IdentityMembers(0).Name
End Function

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

匿名的好友 2024-11-14 03:23:01

您需要使用 Expression.Call

更新 - 不同的重载

Expression.Call(typeof(Enumerable),
                "Contains",
                new Type[] { Expression.Constant(...).Type }
                Expression.Property(...),
                Expression.Constant(...));

You need to use Expression.Call

Update - different overload

Expression.Call(typeof(Enumerable),
                "Contains",
                new Type[] { Expression.Constant(...).Type }
                Expression.Property(...),
                Expression.Constant(...));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文