0

我对 LINQ 有点陌生,如果我的问题很愚蠢,我很抱歉。

我需要从数据库中检索一些值并将它们放入文本框中。只是。类似于下面的代码,但使用 LINQ:

编辑:实际上,我想检索多个字段。像那样:

SqlDataReader dr = new functionThatReturnsDataReader();
if (dr.HasRows) {
    dr.Read();

    txtId = dr["Id"].ToString();
    txtName = dr["Name"].ToString();
}

我在网上找到了这个解决方案

IDbCommand command = dc.GetCommand(query);
command.Connection = dc.Connection;
command.Connection.Open();
IDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection);

但是,如果我将 LINQ 与标准的 executeReader 混合使用,我似乎会抛弃它所代表的一切。没有理由构建数据上下文和查询,它们像 ADO 一样执行它们......

如何在不使用 IDbCommand 和 IDataReader 的情况下达到同样的效果?

4

4 回答 4

1

我认为您需要从数据库中创建一个 LINQ to SQL 类:http: //msdn.microsoft.com/en-us/library/bb384428.aspx

然后您可以将数据库表视为一个对象并使用 linq 对其进行查询...如果没有您尝试运行的查询的详细信息,我无法为您构建 linq 查询,但创建 DBML 文件是第一步。

于 2013-09-18T18:41:24.163 回答
1

将 LINQ(或实体框架,或其他 ORM)解决方案与 ADO.NET 解决方案进行比较时要考虑的一件事是,ORM 通常是强类型的。这意味着您需要对它们应用面向对象的原则。

如果你在同一个函数中处理上下文、查询和结果,你可以这样做:

using(var context = new YourContext())
{
    txtId.Text = (from t in context.YourTable
                  where t.Conditions
                  select t.Id).FirstOrDefault();
}

如果它们不在同一个函数中(实际上,它们不应该是),那么这样的事情会起作用:

string FunctionThatReturnsId()
{
    using(var context = new YourContext())
    {
        return (from t in context.YourTable
                      where t.Conditions
                      select t.Id).FirstOrDefault();
    }
}

...

txtId.Text = FunctionThatReturnsId();
于 2013-09-18T19:19:41.370 回答
0

如果您使用的是实体框架,那么您不需要任何查询,只需在文本框中输入 id 并点击搜索按钮,它将在该 id 的文本框中显示所有记录。

      EntityFramework_mvcEntities db = new EntityFramework_mvcEntities();


        int i =Convert.ToInt32( txtsrch.Text);
        Employee p = db.Employees.Find(i);



        TextBox1.Text = p.Name;
         TextBox2.Text = p.Email;
        TextBox4.Text = p.Mobile;

        db.SaveChanges();
    }
于 2017-08-09T17:35:41.003 回答
-1
var q = from c in context.GetTable<tbl_user>()
    where c.user_ID == lbuserid.Text.ToString()
    select new
    {
        c.Username,
        c.firstname
    };

foreach (var item in q)
{
    lbusername.Text = item.Username;
    lbfirstname.Text = item.firstname;
}
于 2016-07-04T16:34:44.440 回答