データベースにSQLiteを利用する場合の手順はこちらの記事を参照してください。
Install-Package Microsoft.EntityFrameworkCore.Design
Install-Package Microsoft.EntityFrameworkCore.Tools
Scaffold-DbContext '(データベースの接続文字列)' Microsoft.EntityFrameworkCore.SqlServer
(テーブル名).cs
と(データベース名)Context.cs
ファイルが作成されます。(テーブル名).cs
ファイルにはテーブル構造を反映したクラスのコードが生成されています。(データベース名)Context.cs
ファイルにはDbContextを派生したContextクラスのコードが生成されます。id | model | name | class | category | price |
---|---|---|---|---|---|
1 | C-XM01 | モーダンチェア | ホーム | チェア | 56000 |
2 | X-XD05 | ラージデスク | オフィス | テーブル | 87000 |
3 | A-DA40 | ラウンドダイニングチェア | ホーム | チェア | 28000 |
4 | O-XX100 | ナチュラルオフィス | オフィス | チェア | 13800 |
5 | R-D400 | ラウンドダイニングテーブル | ホーム | テーブル | 128000 |
6 | R7000 | ウッドキャビネット | オフィス | その他 | 32000 |
7 | B-200 | リネンベッド | ホーム | ベッド | 184500 |
8 | B-250 | ホワイトダブルベッド | ホーム | ベッド | 324850 |
9 | W-80 | ワーキングチェア | オフィス | チェア | 45000 |
10 | EG-10X | エルゴノミクスデスク | オフィス | テーブル | 88500 |
11 | OC-908 | オーガニックチェア | ホーム | チェア | 56000 |
namespace SimpleEntityFrameworkCoreSqlServer
{
public partial class FormMain : Form
{
public FormMain()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
IPentecSandBoxContext cx = new IPentecSandBoxContext();
IEnumerable<ProductsB> result = cx.ProductsBs;
foreach (ProductsB pb in result) {
textBox1.Text += string.Format("{0:d} - {1} / {2} / {3} / {4} - {5:g}\r\n", pb.Id, pb.Name.Trim(), pb.Model.Trim(), pb.Category.Trim(), pb.Class.Trim(), pb.Price);
}
}
}
}
IPentecSandBoxContext cx = new IPentecSandBoxContext();
ProductsB
)テーブルのデータは、
テーブル名にsを付加した、ProductsBs
プロパティで表現されています。IEnumerable<ProductsB>
のresult
に代入されます。 IEnumerable<ProductsB> result = cx.ProductsBs;
foreach (ProductsB pb in result) {
textBox1.Text += string.Format("{0:d} - {1} / {2} / {3} / {4} - {5:g}\r\n", pb.Id, pb.Name.Trim(), pb.Model.Trim(), pb.Category.Trim(), pb.Class.Trim(), pb.Price);
}