如何将 Linq to SQL 类型传递给函数
下面的代码在 Linq to SQL 解决方案中使用,位于表单的 Load 事件中。
它可以很好地显示人员姓名的有序列表,并将值成员设置为该人员的 ID。
但是,我将经常使用这些“人员”组合框,因此我想将一个子项放入我的实用程序代码中,表单的加载事件中只有一行。
我想调用类似的内容: Call ComboboBoxPeople(cbo, tblTurnbackMain, ReportedByID)
子程序的开头如下: Public Sub ComboboxPeople(cbo as Combobox, tbl as 'sometype', fld as 'someothertype ')
我可以使用什么作为 tbl
和 fld
的参数类型?
'-- cboReportedBy datasource
Dim LQ = (From p In TurnbackDC.vewPeopleAll, t In TurnbackDC.tblTurnbackMain
Where p.PeopleID = t.ReportedByID
Select p.Person, p.PeopleID).Distinct()
Dim LT = From x In LQ
Order By x.Person
Select x.Person, x.PeopleID
cboReportedBy.DataSource = LT
cboReportedBy.DisplayMember = "Person"
cboReportedBy.ValueMember = "PeopleID"
谢谢! 担
The code below is used in a Linq to SQL solution, and is in the Load event of a form.
It works fine to display an ordered list of people's names, and set the value member to that person's ID.
However, I'm going to be using these 'people' comboboxes a lot, so I'd like to put a sub into my Utility code there is only one line in the form's Load event.
I want to call something like: Call ComboboBoxPeople(cbo, tblTurnbackMain, ReportedByID)
The sub would begin like: Public Sub ComboboxPeople(cbo as Combobox, tbl as 'sometype', fld as 'someothertype')
What can I use as the parameter types for tbl
and fld
?
'-- cboReportedBy datasource
Dim LQ = (From p In TurnbackDC.vewPeopleAll, t In TurnbackDC.tblTurnbackMain
Where p.PeopleID = t.ReportedByID
Select p.Person, p.PeopleID).Distinct()
Dim LT = From x In LQ
Order By x.Person
Select x.Person, x.PeopleID
cboReportedBy.DataSource = LT
cboReportedBy.DisplayMember = "Person"
cboReportedBy.ValueMember = "PeopleID"
Thanks!
Dan
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在您的第一个 LINQ 查询中,您定义了一个匿名类型。如果您愿意,您可以将几乎整个代码块(
LQ
和LT
)放入一个方法中并返回 LT。由于LT
包含IEnumerable(Of T)
,其中T
是匿名类型,因此您可以让您的方法仅返回IEnumerable< /code>,如下所示:
这将在 ASP.NET Web 窗体中工作,因为 Web 窗体使用反射从定义的成员(
Person
和PeopleID
)加载数据。然而,这种方法有点脆弱,因为没有编译时支持。因此,另一个选择是定义一个特殊的Class
(我们称之为PersonDTO
),其中包含两个公共属性Person
和PeopleID
> 并让该方法返回一个IEnumerable(Of PersonDTO)
,甚至更好的是一个PersonDTO
对象数组。In your first LINQ query, you are defining an anonymous type. If you want you can put almost the whole code block (both
LQ
andLT
) in a single method and return LT. SinceLT
contains anIEnumerable(Of T)
withT
being an anonymous type, you can let your method simply return anIEnumerable
, as follows:This will work in ASP.NET Web Forms, since Web Forms uses reflection to load the data from members that do define (
Person
andPeopleID
). However, this approach is a bit fragile, since there is no compile time support. Another option therefore is to define a specialClass
(let's call itPersonDTO
) that contains two public propertiesPerson
andPeopleID
and let that method return anIEnumerable(Of PersonDTO)
or even better an array ofPersonDTO
objects.