我使用Visual C#的第二天(经过多年的PHP),我正在尝试访问SQL数据库。
我有“记录”类
public class Class1
{
public int Id { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public decimal Price { get; set; }
}
此类的实例,或此类的实例数组,我想填充数据库Database1.sdf中的数据,表ProductTable:
Id int Primary
Name nvarchar 100
Category nvarchar 100
Price money
所以我做了
SqlCeCommand cmd = new SqlCeCommand("SELECT * FROM ProductTable WHERE id=4");
cmd.Connection = conn;
Class1 row = cmd.
在那里我根本不知道如何继续。与
类似SqlCeCommand cmd = new SqlCeCommand("SELECT * FROM ProductTable");
cmd.Connection = conn;
Class1[] rows = cmd.
从数据库中获取数据对象的首选方法是什么?
答案 0 :(得分:3)
为了一个非常轻巧且易于使用的ORM,请帮助自己,并学会使用某种ORM,我推荐Dapper,你可以这样做:
using (var sqlConnSource = new SqlConnection(SqlSource))
{
sqlConnSource.Open();
var myProducts = sqlConnSource.Query<Class1>("SELECT * FROM Products").ToList();
foreach (var p in myProducts)
{
//do something more useful here if you want
Console.Writeline("The product name is:" + p.Name)
}
}
答案 1 :(得分:1)
如果您不想使用ORM / Entity框架,只需使用C#,
using (SqlCeCommand cmd = new SqlCeCommand("SELECT * FROM ProductTable WHERE id=@val", conn))
{
//read search value from from text field
cmd.Parameters.AddWithValue("@val",<whateverthevalue>);
conn.Open();
SqlCeDataReader reader = cmd.ExecuteReader();
if(reader.Read()) //use while if you want to get multiple records
{
Class1Obj.id= reader.GetString(0);
Calss1Obj.Name= reader.GetString(1);
.....
}
conn.Close();
}