MVVM模式下不使用LINQ,通过SQL查询从SQL加载数据到DataGrid
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
Userclass (most databases are case-insensitive, but matching exactly avoids headaches). - Resource cleanup: The
usingstatement 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

