[英]How do I go about fixing my database table after inserting a list of records different id's corresponding to same name
[英]How can I return a list of objects corresponding to records in my database?
我是C#的新手,我在所有方面都在挣扎,请提供帮助。 这是我正在尝试做的事情:
创建一个数据库类,该类返回一个动态列表,该列表包含一个类的实例,具体取决于要查询的表:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Reflection;
Class MYDatabase{
public void main ()
{
String QueryString="select COLUMN_NAME, DATA_TYPE from information_schema.columns where table_name = 'mytable'";
Object MyData=GetRsults(QueryString,"SchemaStructure");
}
public static Object GetResults(string QueryString, String ClassName)
{
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.CommandText = QueryString;
cmd.CommandType = CommandType.Text;
//assuming I already defined my connection
cmd.Connection = Connection;
Connection.Open();
reader = cmd.ExecuteReader();
Type ClassType = Type.GetType(ClassName);
Type ListType = typeof(List<>).MakeGenericType(new Type[] { ClassType });
Object Results = Activator.CreateInstance(ListType);
Object SingleResult = Activator.CreateInstance(ClassType);
while (reader.Read())
{
for (int i = 0; i < reader.FieldCount; i++)
{
var PropName= SingleResult.GetType().GetProperty(reader.GetName(i).ToString());
//Convert.ChangeType(value, propertyInfo.PropertyType)
PropName.SetValue(PropName,reader.GetValue(i).ToString(),null);
}
Results.Add(SingleResult);
}
Connection.Close();
return Results;
}
}
class SchemaStructure
{
public string COLUMN_NAME { set; get; }
public string DATA_TYPE { set; get; }
}
这行不通, Results.Add(SingleResult);
行Results.Add(SingleResult);
给我一个信息
“对象”不包含“添加”的定义,并且找不到包含接受“对象”类型的第一个参数的扩展方法“添加”(您是否缺少using指令或程序集引用?)
谁能帮我解决此代码?
如果我的方法根本没有道理,我愿意接受其他建议。
谢谢
我想,最重要的是,当您拥有实体框架时,我不会手摇我的POCO对象。 使用NuGet将Entity的最新版本添加到项目中,然后可以右键单击项目并使用Entity的“ Reverse Engineer Code First”功能来构建模型。 当然,这假设您使用的是Entity可以连接到的数据库,并且该数据库已经构建完毕...
您可以在此处阅读有关EF的信息: http : //msdn.microsoft.com/en-us/data/ef.aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.