You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MVVM模式下不使用LINQ,通过SQL查询从SQL加载数据到DataGrid

Convert LINQ-to-SQL to Raw SQL for Your USER Table (MVVM Friendly)

No worries at all—let’s tweak that code to use a raw SQL query instead of LINQ, so you can pull all data straight from your USER table. I’ll keep this simple since you’re new to LINQ and MVVM:

First, make sure your User class matches the columns in your USER table (I’ll go with columns like Login, Password, Permission, LockedAccount based on your original code). Then replace your existing method with this:

public ObservableCollection<User> GetUsers() 
{
    ObservableCollection<User> users = new ObservableCollection<User>();
    try 
    {
        // Wrap the context in a using statement to clean up resources automatically
        using (LinqDataContext dc = new LinqDataContext()) 
        {
            // Raw SQL to fetch every record from the USER table
            string sqlQuery = "SELECT Login, Password, Permission, LockedAccount FROM USER";
            
            // Execute the query and map results directly to your User class
            var userResults = dc.ExecuteQuery<User>(sqlQuery);
            
            // Add all results to the ObservableCollection (works great for DataGrid binding in MVVM)
            foreach (User user in userResults)
            {
                users.Add(user);
            }
        }
    } 
    catch (Exception ex) 
    {
        // Pro tip: Don't just swallow exceptions—log them somewhere (like a debug window or log file)
        // Example: System.Diagnostics.Debug.WriteLine($"Error loading users: {ex.Message}");
        // You could also set a hasError flag here if you need to show an error message in your UI
    }
    return users;
}

Quick Tips for Your MVVM Setup:

  • ObservableCollection is key: This type implements INotifyCollectionChanged, so your DataGrid will automatically update when you add/remove items—perfect for MVVM binding.
  • Column matching: Make sure the column names in your SQL query match the property names in your User class (most databases are case-insensitive, but matching exactly avoids headaches).
  • Resource cleanup: The using statement ensures your database connection is closed properly, which prevents memory leaks.

If Your Table Columns Don’t Match Your Class Properties:

If your USER table has different column names than your User class properties, just alias them in the SQL. For example:

SELECT 
    User_Login AS Login, 
    User_Password AS Password, 
    User_Role AS Permission, 
    Is_Locked AS LockedAccount 
FROM USER

Once you’ve got this method in your view model, just bind the ObservableCollection<User> to your DataGrid’s ItemsSource property, and all your USER table data will show up!

内容的提问来源于stack exchange,提问作者Black Panther

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:33:46