1

我是 LINQ 新手,正在尝试将 Linq to SQL 表绑定到多个控件(树视图、文本框等)。我希望能够更改文本框字段并将这些更新轻松保存回数据库。

我可以使用以下方法从数据库中获取数据:

    Private LinqDB As New DataContext(My.Settings.dbConnection)
    Property tblManufacturers As Table(Of dbManufacturers) _
        = LinqDB.GetTable(Of dbManufacturers)()

将这些东西绑定到控件非常简单。TreeView 填充了所有制造商名称,当我单击一个时,它会填充 TextBoxes 进行编辑。
问题是结果不是我在树视图中想要的顺序。
我希望是这样的:

    Property tblManufacturers As Table(Of dbManufacturers) _
        = LinqDB.GetTable(Of dbManufacturers)().OrderBy("ManufacturerName") 

会工作,但可惜没有。

我知道我可以使用类似的东西

Dim ManufacturerQuery = From ManufacturerName In tblManufacturers Order By ManufacturerName 

但是将更改推回数据库似乎更加困难。

编辑:所以,显然我需要停止懦弱,只是尝试一些东西......

Namespace Controls
    Public Class ManufacturerWarranty

        Private LinqDB As New DataContext(My.Settings.dbConnection)
        Property tblManufacturers As Table(Of dbManufacturers) = LinqDB.GetTable(Of dbManufacturers)()
        Property ManufacturerQuery = From m In tblManufacturers Order By m.ManufacturerName

        Public Sub New()
            InitializeComponent()
        End Sub

        Private Sub ManufacturerWarranty_Loaded(sender As Object, e As System.Windows.RoutedEventArgs) Handles Me.Loaded
            Me.DataContext = Me
        End Sub

        Private Sub TreeView1_MouseDoubleClick(sender As System.Object, e As System.Windows.Input.MouseButtonEventArgs) Handles TreeView1.MouseDoubleClick
            StackPanel1.DataContext = e.OriginalSource.DataContext
        End Sub


        Private Sub cmdSave_Click(sender As Object, e As System.Windows.RoutedEventArgs) Handles cmdSave.Click
            LinqDB.SubmitChanges()
        End Sub
    End Class
End Namespace

然后我只是将我的 TreeView 绑定到 ManufacturerQuery 而不是 tblManufacturers。我的保存按钮仍然适用于提交更改,即使它们是针对 ManufacturerQuery 而不是 tblManufacturers 进行的。

4

1 回答 1

1

好吧,也许你想要

Dim tblManufacturers As Table(Of dbManufacturers) _
    = LinqDB.GetTable(Of dbManufacturers)() _
        .OrderBy(Function(m) m.ManufacturerName)  

所以,承诺你会做

Using linqDB As New DataContext(My.Settings.dbConnection)
    Dim tblManufacturers As Table(Of dbManufacturers) _
        = linqDB.GetTable(Of dbManufacturers)()

    -- change tblManufacturers.

    linqDB.SaveChanges()
End Using

我不会做的是在用户与 GUI 交互时保持上下文打开。同样,除非我将数据显示给用户,否则我(可能)不会订购数据。

于 2012-10-22T14:11:41.557 回答