0

LINQを使用してリテラルコントロールに値を設定したい。次のコードでvarのデータベースから結果を取得しました。

var result=md.StoredProc_Name(id);

ここで、特定の列の値をリテラルに割り当てたいと思います。datatableを使用すると、次のように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 に答える