在C# .NET5中如何将List<>、DataTable或DataRow的数据映射到实体模型类以直接调用属性赋值?
EmployeeModel to Populate UI Controls: Feasible and Highly Recommended! Absolutely, using an EmployeeModel instance directly to set your text box values is not only feasible but also a much cleaner, maintainable approach than converting to a DataTable first. It aligns with object-oriented principles and cuts down on redundant code. Let's break down how to implement this for your specific scenarios in .NET 5.
1. Mapping List<EmployeeModel> to UI Controls
Your original code fetches a List<EmployeeModel> but then converts it to a DataTable to pull values. Instead, you can directly use the EmployeeModel instance from the list (since you're querying by EmployeeId, the list should contain at most one item).
Modified Code Example
private void comboBoxSelectEmployee_SelectionChangeCommitted(object sender, System.EventArgs e) { this.EmployeeModel.EmployeeId = comboBoxSelectEmployee.SelectedValue.ToString(); var employeeList = EmployeeInfoCollection.GetWhereEmployeeId(this.EmployeeModel.EmployeeId); // Grab the first (and likely only) employee from the results var selectedEmployee = employeeList.FirstOrDefault(); if (selectedEmployee != null) { // Directly use model properties to populate your controls textBoxLicensePlate1.Text = selectedEmployee.LicensePlate1; textBoxLicensePlate2.Text = selectedEmployee.LicensePlate2; textBoxFirstname.Text = selectedEmployee.Firstname; textBoxLastname.Text = selectedEmployee.Lastname; textBoxNickname.Text = selectedEmployee.Nickname; textBoxPhoneNumber.Text = selectedEmployee.PhoneNumber; textBoxBank.Text = selectedEmployee.Bank; textBoxAccountNumber.Text = selectedEmployee.AccountNumber; textBoxPromptpay.Text = selectedEmployee.Promptpay; } else { // Handle empty result case (clear controls or show a message) textBoxLicensePlate1.Text = string.Empty; textBoxLicensePlate2.Text = string.Empty; // ... clear other controls similarly } }
- Key Notes:
- Use
FirstOrDefault()instead of casting the list directly to avoid exceptions if the list is empty. - Always check if
selectedEmployeeis not null before accessing its properties to preventNullReferenceException.
- Use
2. Mapping a DataRow to EmployeeModel
For converting a single DataRow to your EmployeeModel, you have two solid approaches: manual mapping (no external libraries) or using AutoMapper to automate the process.
Option 1: Manual Mapping (Simple & Self-Contained)
Create an extension method to convert a DataRow to EmployeeModel:
public static class EmployeeExtensions { public static EmployeeModel ToEmployeeModel(this DataRow row) { if (row == null) return null; return new EmployeeModel { EmployeeId = row["EmployeeId"].ToString(), LicensePlate1 = row["LicensePlate1"].ToString(), LicensePlate2 = row["LicensePlate2"].ToString(), Firstname = row["Firstname"].ToString(), Lastname = row["Lastname"].ToString(), Nickname = row["Nickname"].ToString(), PhoneNumber = row["PhoneNumber"].ToString(), Bank = row["Bank"] != DBNull.Value ? row["Bank"].ToString() : string.Empty, AccountNumber = row["AccountNumber"].ToString(), Promptpay = row["Promptpay"].ToString() }; } }
Then use it in your code like this:
// Assume EmployeeRowValue is your target DataRow var row = EmployeeRowValue.ToEmployeeModel(); if (row != null) { comboBoxSelectEmployee.SelectedValue = row.EmployeeId; this.EmployeeModel.EmployeeId = row.EmployeeId; textBoxLicensePlate1.Text = row.LicensePlate1; textBoxLicensePlate2.Text = row.LicensePlate2; // ... rest of the control assignments }
Option 2: Using AutoMapper (Automates Repetitive Mapping)
If you have many models or want to avoid writing manual mapping code, use AutoMapper (a popular object-to-object mapping library):
- Install AutoMapper:
Install-Package AutoMapper - Configure the Mapping Profile:
public class MappingProfile : Profile { public MappingProfile() { CreateMap<DataRow, EmployeeModel>() .ForMember(dest => dest.EmployeeId, opt => opt.MapFrom(src => src["EmployeeId"].ToString())) .ForMember(dest => dest.Bank, opt => opt.MapFrom(src => src["Bank"] != DBNull.Value ? src["Bank"].ToString() : string.Empty)) // AutoMapper will match other properties automatically if their names are identical .ReverseMap(); // Optional, if you need to map from model back to DataRow } } - Initialize and Use AutoMapper:
// Initialize once (e.g., in your startup or form constructor) var config = new MapperConfiguration(cfg => cfg.AddProfile<MappingProfile>()); var mapper = config.CreateMapper(); // In your UI code: var row = mapper.Map<EmployeeModel>(EmployeeRowValue); if (row != null) { // Populate controls using the mapped model }
3. Mapping a DataTable to List<EmployeeModel>
If you need to convert an entire DataTable to a list of EmployeeModel, extend the manual mapping approach:
public static List<EmployeeModel> ToEmployeeList(this DataTable table) { if (table == null || table.Rows.Count == 0) return new List<EmployeeModel>(); var employees = new List<EmployeeModel>(); foreach (DataRow row in table.Rows) { employees.Add(row.ToEmployeeModel()); } return employees; }
Or use AutoMapper to map the DataTable directly to a List<EmployeeModel> with minimal code.
Final Thoughts
Using EmployeeModel directly eliminates the unnecessary overhead of converting to/from DataTable, making your code more efficient and easier to debug. Always remember to handle null values and DBNull cases to avoid runtime exceptions.
内容的提问来源于stack exchange,提问作者MR.niceman

