您好我已经创建了一个类来从客户的帐户表中获取值,我已经为此创建了一个类。我想通知AccountId和我想要结果的表的字段(例如FirstName)。实现这一目标的最佳方法是什么?我得到了类似下面的东西作为我的替代方案,但我不能让它起作用......
这就是我想要得到名字的结果:
LabelFirstName.Text = Manage.GetAccount(2, "FirstName"); // where 2 is the id I informed and FirstName is the Column I want to retrieve from the table.
例如,结果将是“约翰”。
public class Manage
{
public Manage()
{
}
public static string GetAccount(int AccountId, string Field)
{
LinqSqlDataContext contextLoad = new LinqSqlDataContext();
var q = (from p in contextLoad.MyAccounts
where p.AccountId == AccountId
select p).Single();
string var = q.?? // ?? would be my Field string "FirstName" for example
return var;
}
}
请帮忙
由于
答案 0 :(得分:1)
我建议您返回Account对象,然后在需要的地方检索属性,如下所示:
public static Account GetAccount(int AccountId)
{
LinqSqlDataContext contextLoad = new LinqSqlDataContext();
var q = (from p in contextLoad.MyAccounts
where p.AccountId == AccountId
select p).Single();
return q;
}
public void myMethod()
{
var account = GetAccout(2);
var accountName = account.FirstName;
var accountNumber = account.Number;
// ... and so on
}
如果这实际上没有帮助,您可以使用其他帖子中提到的反射。
祝你好运。答案 1 :(得分:0)
您可以返回班级的对象
public static Object GetAccount(int AccountId)
{
LinqSqlDataContext contextLoad = new LinqSqlDataContext();
var q = (from p in contextLoad.MyAccounts
where p.AccountId == AccountId
select p).FirstOrDefault();
return q;
}
var Account = GetAccount(int AccountId) as Account;
LabelFirstName.Text = Account.FirstName;
LabelLastName.Text = Account.LastName;
你可以从对象获得所有的领域!因此,可以通过一次数据库调用
实现任务答案 2 :(得分:0)
string value = (string)q.GetType().GetProperty(Field).GetValue(q, null);
答案 3 :(得分:0)
在这种情况下,DataReader可能很有用:
var q = from p in contextLoad.MyAccounts
where p.AccountId == AccountId
select p;
using (var command = dc.GetCommand(q))
{
command.Connection.Open();
using (var reader = command.ExecuteReader())
{
// expecting one row
if(reader.Read())
{
return reader.GetString(reader.GetOrdinal(Value));
}
}
return null;
}