c# - 如何修复列'CourseNum'不属于表
问题描述
我有一个数据库,它的表名CourseOffered如下所示:
我要选择的唯一列(要返回的请求)是学期并将其添加到下拉列表中。这是我在存储库类中的代码。
public List<CoursesOffered> GetSemester()
{
List<CoursesOffered> SemestersName = null;
try
{
string sql = "SELECT DISTINCT Semester FROM CoursesOffered";
DataTable dt = _idac.GetManyRowsCols(sql, null);
SemestersName = DBList.ToList<CoursesOffered>(dt);
}
catch (Exception)
{
throw;
}
return SemestersName;
}
我正在从我的DataAccess 类中调用GetManyRowsCols() ,并且我有一个看起来像这样的DBList和实体类。
class DBList
{
public static List<T> ToList<T>(DataTable dt)
where T : IEntity, new()
{
List<T> TList = new List<T>();
foreach (DataRow dr in dt.Rows)
{
T tp = new T();
tp.SetFields(dr);
TList.Add(tp);
}
return TList;
}
}
public class EntityBase : IEntity
{
public void SetFields(DataRow dr)
{
// use reflection to set the fields from DataRow
Type tp = this.GetType();
foreach (PropertyInfo pi in tp.GetProperties())
{
if (null != pi && pi.CanWrite)
{
string nm = pi.PropertyType.Name.ToUpper();
if (nm.IndexOf("ENTITY") >= 0)
// In LINQ to SQL Classes, last properties are links to other tables
break;
if (pi.PropertyType.Name.ToUpper() != "BINARY")
pi.SetValue(this, dr[pi.Name], null);
}
}
}
}
这就是我尝试将其添加到下拉列表的方式,
private void CourseManagement_Load_1(object sender, EventArgs e)
{
try
{
List<CoursesOffered> semesterList = _ibusinessSemester.GetSemester();
cbCourseNumberDropDown.DataSource = semesterList;
cbCourseNumberDropDown.Refresh();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
但我不断收到一条错误消息,提示“CourseNum”列不属于该表
解决方案
根据您的描述,您希望将一列转换为列表。
由于我没有关于 的代码IEntity
,因此无法测试您的代码。
但是,我制作了以下代码来实现它。
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var list = DBList.ToList<string>(table, "Semeter").Distinct().ToList();// the code I have modified
comboBox1.DataSource = list;
}
DataTable table = new DataTable();
private void Form1_Load(object sender, EventArgs e)
{
table.Columns.Add("Course",typeof(string));
table.Columns.Add("Semeter", typeof(string));
table.Columns.Add("MaxEncrollment", typeof(int));
table.Rows.Add("CPSC 410","Fall 2016",35);
table.Rows.Add("CPSC 411", "Fall 2016", 30);
table.Rows.Add("CPSC 440", "Fall 2016", 35);
table.Rows.Add("Math301", "Fall 2016", 35);
}
}
class DBList
{
public static List<T> ToList<T>(DataTable dt,string columnname)
{
List<T> TList = new List<T>();
TList = dt.AsEnumerable().Select(r => r.Field<T>(columnname)).ToList();
return TList;
}
}
推荐阅读
- woocommerce - 在产品类别概述的标题下显示 Woocommerce 产品的元描述
- java - 如何放入动态值并将其保存在HashMap中?
- javascript - Jquery Ajax 标头更改标头键
- flutter - 我已经创建了我的 search_dart 文件,但我不断收到这个抖动错误 LateInitializationError: Field 'docsSnap' has not been initialized
- angular - 从Angular中的子组件更改祖先类
- amazon-web-services - 无法为 S3 中的日志跨账户写入创建存储桶策略
- reactjs - 将 cookie 添加到 axios 拦截器请求处理程序
- c++ - Clang:-Wdangling-gsl 和花括号初始化没有警告,clang 中的错误?
- azure - 如何验证 Azure AD 令牌?
- ios - Xamarin iOS:使用 iOS 15 将应用程序部署到设备或模拟器