0

我想使用 LINQ 将值设置为文字控件。我通过以下代码从 var 中的数据库中获得了结果:

var result=md.StoredProc_Name(id);

现在我想将特定的列值分配给文字。正如我们可以在数据表的帮助下在 asp.net 中简单地做的那样,

dt=obj.Test(id);
ltrlName.Text=dt.Rows[0]["Name"].ToString();
ltrlAddress.Text=dt.Rows[0]["Address"].ToString();

我们如何在 LINQ 中做同样的事情?

4

1 回答 1

1
var first = result.FirstOrDefault();

if (first != null)
{
   ltrlName.Text = first.Name;
   ltrlAddress.Text = first.Address;
}

附录 - 如何在没有 linq 到对象的情况下执行此操作:

在名为 DB 的类中使用下面的代码

var result = DB.SelectIntoItem("StoredProc_Name",
                               connectionString,
                               System.Data.CommandType.StoredProcedure,
                               new { param1 = "val1" });

if (!reader.Empty)
{
   ltrlName.Text=result.Name;
   ltrlAddress.Text=result.Address;
}
etc.

代码

public static dynamic SelectIntoItem(string SQLselect, string connectionString, CommandType cType = CommandType.Text, object parms = null)
{
  using (SqlConnection conn = new SqlConnection(connectionString))
  {
    using (SqlCommand cmd = conn.CreateCommand())
    {
      dynamic result = new System.Dynamic.ExpandoObject();

      cmd.CommandType = cType;
      cmd.CommandText = SQLselect;

      if (parms != null)
        Addparms(cmd, parms);

      conn.Open();


      using (SqlDataReader reader = cmd.ExecuteReader())
      {
        if (reader.Read())  // read the first one to get the columns collection
        {
          var cols = reader.GetSchemaTable()
                       .Rows
                       .OfType<DataRow>()
                       .Select(r => r["ColumnName"]);

          foreach (string col in cols)
          {
            ((IDictionary<System.String, System.Object>)result)[col] = reader[col];
          }
          result.Empty = false;

          if (reader.Read())
          {
            // error, what to do?
            result.Error = true;
            result.ErrorMessage = "More than one row in result set.";
          }
          else
          {
            result.Error = false;
          }

        }
        else
        {
          result.Empty = true;
          result.Error = false;
        }
      }

      conn.Close();

      return result;
    }
  }
}

private static void Addparms(SqlCommand cmd, object parms)
{
  // parameter objects take the form new { propname : "value", ... } 
  foreach (PropertyInfo prop in parms.GetType().GetProperties())
  {
    cmd.Parameters.AddWithValue("@" + prop.Name, prop.GetValue(parms, null));
  }
}

如果你有兴趣关注我的 GitHub,我会尽快将其余部分公开(GitHub

于 2012-07-07T16:14:30.420 回答