Entity Framework を利用して一つのレコードを検索するコードを紹介します。
概要
Entity Framework で一つのレコードを取得する場合は、Singleメソッドを利用します。検索条件がある場合は、Singleメソッドの引数に検索条件式やメソッドを与えます。
プログラム例
テーブル
データベースに下記のテーブルを作成します。
ProductAテーブル レコード
id | name | price | category |
1 | Penguin | 500 | Bird |
2 | Bear | 1050 | Mammal |
3 | Duck | 150 | Bird |
4 | Camel | 550 | Mammal |
5 | Owl | 185 | Bird |
6 | Whale | 880 | Mammal |
データモデルの作成
こちらの記事を参照して、CodeFirst形式でデータモデルを作成します。
UI
下図のUIを作成します。フォームにテキストボックス2つとボタンを1つ配置します。
コード
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace EntityFrameworkDBOperationDemo
{
public partial class FormSingle : Form
{
public FormSingle()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
ModelProductsA model = new ModelProductsA();
int searchID = Convert.ToInt32(textBox1.Text);
ProductsA item = model.ProductsA.Single(p => p.id == searchID);
textBox2.Text += string.Format("ID:{0:d}\r\n",item.id);
textBox2.Text += string.Format("name:{0}\r\n", item.name.Trim());
textBox2.Text += string.Format("price:{0:g}\r\n", item.price);
textBox2.Text += string.Format("category:{0}\r\n", item.category);
}
}
}
解説
下記コードで、モデルオブジェクトを作成します。
ModelProductsA model = new ModelProductsA();
上部のテキストボックスに入力された検索したいidを数値に変換しsearchID変数に格納します。
int searchID = Convert.ToInt32(textBox1.Text);
モデルオブジェクトのテーブルオブジェクトのSingleメソッドを呼び出しテーブルを検索してレコードを1つ取得します。Singleメソッドの引数には検索条件のラムダ式を与えます。今回の例では、idの値が先ほど格納したsearchID と一致するレコードを検索する動作になります。検索結果により取得されたレコードオブジェクトがSingleメソッドの戻り値として返ります。
ProductsA item = model.ProductsA.Single(p => p.id == searchID);
検索結果で取得できたレコードのフィールド値が、レコードオブジェクトのプロパティに格納されていますので、その値をテキストボックスに表示します。
textBox2.Text += string.Format("ID:{0:d}\r\n",item.id);
textBox2.Text += string.Format("name:{0}\r\n", item.name.Trim());
textBox2.Text += string.Format("price:{0:g}\r\n", item.price);
textBox2.Text += string.Format("category:{0}\r\n", item.category);
実行結果
プロジェクトを実行します。下図のウィンドウが表示されます。
上部のテキストボックスに検索したいIDを入力します。今回は"3"を入力します。
[button1]をクリックします。id=3 のレコードが取得され、フィールドの値が下部のテキストボックスに表示されます。
Singleメソッドを利用して検索条件に一致するレコードを1つ取得するプログラムができました。
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2024-01-06
作成日: 2019-01-25