テンプレートテスト
ブログの説明
ブログの説明2
menu
keyboard_arrow_up
Top
search
close
home
ホーム
computer
PC一般
construction
開発環境・ツール
code
プログラミング
home
ホーム
computer
PC一般
construction
開発環境・ツール
code
プログラミング
Home
›
Archives for 1月 2018
2018/01/30
image
NO IMAGE
Entity Framework Core におけるデータの保存
update
event_note
label
C#
label
Entity Framework Core
Entity Framework Core におけるデータの基本的な保存方法と、エンティティ同士が関連している場合のデータの保存方法についてです。
公式サイトに詳しい解説があるので、ほとんど訳しただけになってしまいました・・・。 - https://docs.microsoft.com/en-us/ef/core/saving/basic - https://docs.microsoft.com/en-us/ef/core/saving/related-data 訳が微妙なので、原文を読まれたほうが良いかもしれません。 ## 環境 - Visual Studio 2017 - .NET Core 2.0 - Entity Framework Core 2.0 ## 扱うモデル 公式サイトと同じ、以下のモデルを基本的な例とします。 (場合によっては別の例が挙げられていますが・・・) ```cs // Blog is the principal entity public class Blog { // Blog.BlogId is the principal key // (in this case it is a primary key rather than an alternate key) public int BlogId { get; set; } public string Url { get; set; } // Blog.Posts is a collection navigation property public List
Posts { get; set; } } // Post is the dependent entity public class Post { public int PostId { get; set; } public string Title { get; set; } public string Content { get; set; } // Post.BlogId is the foreign key public int BlogId { get; set; } // Post.Blog is a reference navigation property // Post.Blog is the inverse navigation property of Blog.Posts (and vice versa) public Blog Blog { get; set; } } ``` ## 基本操作 ### データの追加 `DbSet.Add` メソッドを使用して、エンティティクラスの新しいインスタンスを追加します。 `SaveChanges` を呼び出すと、データがデータベースに挿入されます。 ```cs using (var context = new BloggingContext()) { var blog = new Blog { Url = "http://sample.com" }; context.Blogs.Add(blog); context.SaveChanges(); Console.WriteLine(blog.BlogId + ": " + blog.Url); } ``` ### データの更新 EF は、コンテキストによって追跡される既存のエンティティに対する変更を自動的に検出します。 これには、データベースから取得または照会するエンティティ、および以前にデータベースに追加および保存されたエンティティが含まれます。 従って、プロパティに割り当てられた値を変更したら、`SaveChanges` を呼び出すだけでデータを更新できます。 ```cs using (var context = new BloggingContext()) { var blog = context.Blogs.First(); blog.Url = "http://sample.com/blog"; context.SaveChanges(); } ``` ここで、以下のようにインスタンスを丸ごと差し替えてしまうとデータの更新は反映されないので、やってはいけません。 ```cs using (var context = new BloggingContext()) { var blog = context.Blogs.First(); // これだとデータは更新されない blog.Url = new Blog { Url = "http://sample.com" }; context.SaveChanges(); } ``` 必ずプロパティ毎にデータをセットする必要があります。 ### データの削除 エンティティクラスのインスタンスを削除するには、`DbSet.Remove` メソッドを使用します。 エンティティがデータベースに存在する場合、`SaveChanges` の実行中に削除されます。 エンティティがまだデータベースに保存されていない(追加されたとして追跡されている)場合、そのエンティティはコンテキストから削除され、`SaveChanges` が呼び出されると挿入されなくなります。 ```cs using (var context = new BloggingContext()) { var blog = context.Blogs.First(); context.Blogs.Remove(blog); context.SaveChanges(); } ``` ### 1つの SaveChanges での複数の操作を行う 複数の `Add` `Update` `Remove` の操作を1つの `SaveChanges` に対して組み合わせることもできます。 尚、ほとんどのデータベースプロバイダーにおいて、`SaveChanges` はトランザクショナルです。 これは、すべての操作が成功または失敗のどちらかであり、操作が部分的に適用されることはないということを意味します。 ```cs using (var context = new BloggingContext()) { // seeding database context.Blogs.Add(new Blog { Url = "http://sample.com/blog" }); context.Blogs.Add(new Blog { Url = "http://sample.com/another_blog" }); context.SaveChanges(); } using (var context = new BloggingContext()) { // add context.Blogs.Add(new Blog { Url = "http://sample.com/blog_one" }); context.Blogs.Add(new Blog { Url = "http://sample.com/blog_two" }); // update var firstBlog = context.Blogs.First(); firstBlog.Url = ""; // remove var lastBlog = context.Blogs.Last(); context.Blogs.Remove(lastBlog); context.SaveChanges(); } ``` ## 関連データの保存 リレーションシップについては以下の記事に書いているので、そちらを参照してください。 - [Entity Framework Core におけるリレーションシップについて](http://kuttsun.blogspot.jp/2018/01/entity-framework-core_11.html) ### 新規作成 英語では **Adding a graph of new entities** と書かれていました。 - https://docs.microsoft.com/en-us/ef/core/saving/related-data 親のテーブルに新規にレコードを作成し、その子となるテーブルにもレコードを作成することを、エンティティのグラフを追加すると表現しているようですね。 以下がコードの例です。 ```cs using (var context = new BloggingContext()) { var blog = new Blog { Url = "http://blogs.msdn.com/dotnet", Posts = new List
{ new Post { Title = "Intro to C#" }, new Post { Title = "Intro to VB.NET" }, new Post { Title = "Intro to F#" } } }; context.Blogs.Add(blog); context.SaveChanges(); } ``` この場合、`Blogs` のテーブルと `Posts` のテーブルにそれぞれデータが挿入されます。 `Blog` クラスには `Posts` という Navigation property があるため、`Blogs` テーブルと `Posts` テーブルのリレーションシップは EF Core によって自動的に解決されます。 ### 関連するエンティティの追加 Navigation property に新規にエンティティを追加すると、関連するテーブルに自動的にレコードが追加されます。 以下がコード例です。 ```cs using (var context = new BloggingContext()) { var blog = context.Blogs.Include(b => b.Posts).First(); var post = new Post { Title = "Intro to EF Core" }; blog.Posts.Add(post); context.SaveChanges(); } ``` データベースからフェッチされた `Blog` エンティティの `Posts` プロパティに新しくデータを追加しています。 この結果、データベースの `Posts` テーブルにもレコードが追加されます。 ### リレーションシップの変更 エンティティの Navigation property を変更すると、対応する変更がデータベースの外部キー列に対して行われます。 次の例では、`post` エンティティは新しい `blog` エンティティに属するように更新されます。 Navigation property である `post.Blog` に新しい `blog` エンティティをセットしているからです。 また、`blog` はデータベースにも挿入されることに注意してください。 `blog` はすでにコンテキスト(`post`)によって追跡されているエンティティの Navigation property から参照されている新しいエンティティであるためです。 ```cs using (var context = new BloggingContext()) { var blog = new Blog { Url = "http://blogs.msdn.com/visualstudio" }; var post = context.Posts.First(); post.Blog = blog; context.SaveChanges(); } ``` ### リレーションシップの削除 リレーションシップを削除するには、Navigation propery を `null` に設定するか、関連するエンティティを Navigation propery のコレクションからから削除します。 リレーションシップを削除すると、そのリレーションシップで設定されたカスケード削除動作に従って、エンティティの依存関係に副作用が生じる可能性があります。 デフォルトでは、必要な関係に従ってカスケード削除動作が設定され、子エンティティと依存エンティティがデータベースから削除されます。 そのリレーションシップがオプションの関係の場合、カスケード削除はデフォルトでは設定されていませんが、外部キーのプロパティは `null` に設定されます。 リレーションシップの必要性の設定方法については、[Required and Optional Relationships](https://docs.microsoft.com/en-us/ef/core/modeling/relationships#required-and-optional-relationships) を参照してください。 カスケード削除動作の仕組み、それを明示的に設定する方法、EF の規則によってどのように選択されるかの詳細については、[Cascade Delete](https://docs.microsoft.com/en-us/ef/core/saving/cascade-delete) を参照してください。 次の例では、カスケード削除が `Blog` と `Post` の関係に対して設定されているので、`post` エンティティはデータベースから削除されます。 ```cs using (var context = new BloggingContext()) { var blog = context.Blogs.Include(b => b.Posts).First(); var post = blog.Posts.First(); blog.Posts.Remove(post); context.SaveChanges(); } ```
Read more
2018/01/29
image
NO IMAGE
Moq のインストール
update
event_note
label
Visual Studio
テストコードを書く際、IO 処理を含んでいたりするとテストコードを書きづらいため、そういうときはモックを作成したりするそうです。 .NET では Moq というフレームワークがあるので、テストコードを書く際にはそれを使用しています。
## 環境 - Visual Studio 2017 ## インストール NuGet パッケージマネージャーコンソールで、以下のコマンドを実行します。 テストプロジェクトにインストールします。 ```sh PM> Install-Package Moq ``` ## 使い方 以下の記事を参照してみてください。 - [MSTest と Moq を使用した単体テスト](http://kuttsun.blogspot.jp/2017/07/mstest-moq.html)
Read more
2018/01/22
ASP.NET Core で SignalR を使用する
update
event_note
label
ASP.NET Core
label
SignalR
ASP.NET Core で WebSocket を使おうと思ったら SignalR Core というものがあるのを知ったので、試してみました。
尚、WebSocket は昔に Node.js と Socket.IO を使ってみたことがあるのですが、SignalR は初めて触ります。 ## 環境 - Visual Studio 2017 - ASP.NET Core 2.0 ASP.NET Core 2.0 の MVC テンプレートプロジェクトをベースとします。 ## サーバーサイドの実装 ### SignalR Core のインストール NuGet パッケージマネージャーコンソールで以下のコマンドでインストールします。 (現在は alpha 版なので、`-pre` をつけてインストールする必要があります。) ```sh PM> Install-Package Microsoft.AspNetCore.SignalR -pre ``` ### Hub クラスの作成 SignalR ではPersistent Connection と Hub という2つの通信モデルがあるようです。 - http://www.atmarkit.co.jp/ait/articles/1303/19/news099_2.html 今回は Hub を使用します。 `SignalR.Hub` を継承したクラスを作成します。 ``` using Microsoft.AspNetCore.SignalR; // 中略 public class SignalRTest : Hub { public Task Send(string data) { return Clients.All.InvokeAsync("AddMessage", data); } } ``` これで API が RPC として実装され、外部から `Send` メソッドが使用可能となります。 ### Startup.cs の変更 SignalR を使用するための準備として、`Startup` クラスの `ConfigureServices` メソッドに `AddSignalR` を追加します。 ```cs public void ConfigureServices(IServiceCollection services) { services.AddSignalR();// <-- SignalR services.AddMvc(); } ``` また、`Startup` クラスの `Configure` メソッドに `UseSignalR` を以下のように追加します。 ```cs app.UseSignalR(routes => // <-- SignalR { routes.MapHub
(nameof(SignalRTest)); }); ``` ここまで実装した状態でプログラムを実行し、`http://localhost:xxxxx/SignalR` を開いたときに `Connection ID required` と表示されれば正常です。 ## クライアントサイドの実装 SignalR の JavaScript Client を使用します。 ### SignalR Client のインストール ASP.NET Core では SignalR の JavaScript 用クライアントも新しくなっているようです。 - https://blogs.msdn.microsoft.com/webdev/2017/09/14/announcing-signalr-for-asp-net-core-2-0/ ASP.NET Core ではフロントエンドのパッケージ管理は Bower で管理されていましたが、現在では Bower は非推奨となっているので、この新しい SignalR Client も Bower では提供されていないようです。 なので、上記のサイトに書いてある通り、npm でインストールします。 ```sh npm install @aspnet/signalr-client ``` インストールが完了したら、`signalr-client.js` をプロジェクト配下の `wwwroot/js` にコピーします。 尚、現在ではまだ alpha 版なので、ファイル名は `signalr-client-1.0.0-alpha2-final.js` のようになっています。 ### View の追加 ASP.NET Core の MVC テンプレートプロジェクトに対して、`Views/Home/SignalR.cshtml` というファイルを作成しました。 #### Script の読み込み 従来の SignalR では、Script ファイルに加えて、SignalR が動的に生成する `~/signalR/hubs` というフォルダも読み込む必要があったようですが、SignalR Core では不要になったようです。 なので、以下の一行で OK です。 ```html ``` ASP.NET Core の MVC テンプレートプロジェクトでは、`_Layout.cshtml` に以下のセクションが定義されています。 ``` @RenderSection("Scripts", required: false) ``` 従って、SignalR を使用したい View で、Script セクションを作成し、そこで SignalR の Script を読み込ませたいと思います。 セクションについては以下を参照してください。 - http://www.atmarkit.co.jp/fdotnet/aspnetmvc3/aspnetmvc3_08/aspnetmvc3_08_02.html `SignalR.cshtml` に以下を記述します。 ```cs @section scripts {
} ``` #### SignalR の使用 まずは簡単なサンプルとして、上記のコードに以下のようなコードを追加しました。 ```html @section scripts {
} ``` `signalR.HubConnection` で `Hub` クラスを継承したクラスを指定します。 `connection.invoke('send', 'Hello');` で、Hub クラス内の `Send` メソッドをコールしています。 `connection.on('AddMessage',...);` で、`AddMessage` というメッセージを受信したときの処理を定義しています。 ### Controller の変更 `HomeController.cs` に以下の View に対応したアクションメソッドを追加しました。 ```cs public IActionResult SignalR() { return View(); } ``` ### とりあえず実行 以上まで実装し、デバッガを起動し、`/Home/SignalR` にアクセスします。 デバッガのコンソールログには以下のように出力されます。
### メッセージの送信ボタンを実装 `SignalRTest.cshtml` を以下のように変更してみます。 ```html @{ ViewData["Title"] = "SignalR Test"; } @section scripts {
}
SignalR Test
``` 実行結果は以下のようになります。
## 感想 SignalR Core はまだ正式リリース前であり、また ASP.NET Core 自体の情報が少ないこともあり、ここまで動くようにするだけでも結構苦労しました。 しかし、実際動いたコードだけをみると、とても簡単に双方向通信が実現できて便利だなと思いました。 ## 参考 URL **SignalR** - https://docs.microsoft.com/en-us/aspnet/core/fundamentals/websockets - http://blog.livedoor.jp/monthly_check/archives/70912403.html - http://matsujirushi.hatenablog.jp/entry/2017/09/29/232258 - https://blogs.msdn.microsoft.com/webdev/2017/09/14/announcing-signalr-for-asp-net-core-2-0/ **WebSocket** - http://tamafuyou.hatenablog.com/entry/aspnetcore_websocket_vue_sample - http://zbrad.github.io/tools/wscore/ - https://blog.masuqat.net/2016/06/10/asp-net-core-websocket/
Read more
2018/01/20
Firefox で英単語を簡単に調べられるアドオン
update
event_note
label
Firefox
label
英語
Firefox Quantum に対応した、英単語の意味を簡単に調べられるアドオンがないかなと探して、Pop-Up Dictionary というのを見つけたので、これを使って Weblio で単語の意味を調べられるようにしました。
まずは以下からアドオンをインストールします。 - [Pop-Up Dictionary](https://addons.mozilla.org/ja/firefox/addon/pop-up-dictionary/) インストールが完了したら、ブラウザの右上に P マークのアイコンが表示されるのでクリックし、[Settings] を選択します。 [Add Dictionary] をクリックし、以下のように入力して保存します。
URL は `https://ejje.weblio.jp/content/$$` と指定します。 幅と高さは環境に合わせて変更すればよいと思います。 これで、ブラウザ上で単語を選択状態にすると `Open PUD` というボタンが表示されるので、クリックすると Weblio の画面が表示されます。 Weblio に限らず、自分の好きなサイトを指定できるのもよいですね。
Read more
2018/01/18
image
NO IMAGE
画像を svg から emf に変換する
update
event_note
label
Windows
会社では PowerPoint 2010 を使用しているのですが、SVG に対応していないので、ベクター画像を挿入したい場合は emf に変換してから挿入します。
画像形式の変換には [Inkscape](https://inkscape.org/ja/download/) を使用します。 [Inkscape](https://inkscape.org/ja/download/) をインストールしたら、以下のようなバッチファイルを作成します。 ```sh @echo off set inkscape="C:\Program Files\Inkscape\inkscape.exe" for %%f in (%*) do ( echo %%f を変換中 %inkscape% %%f -M %%~nf.emf echo %%f の変換完了 ) ``` これで、変換したいファイルをバッチファイルにドラッグ&ドロップするだけで、複数のファイルを一括で emf に変換できます。 ## 参考 URL - http://maku77.github.io/windows/powerpoint/svg2emf.html
Read more
2018/01/17
image
NO IMAGE
Entity Framework Core におけるデータの取得
update
event_note
label
Entity Framework Core
Entity Framework Core を使ってデータベースからデータを取得する方法についてです。
## 環境 - Visual Studio 2017 - .NET Core 2.0 - Entity Framework Core 2.0 ## 基本 ### 全データの取得 ```cs using (var context = new BloggingContext()) { var blogs = context.Blogs.ToList(); } ``` ### 単一のエンティティ(レコード)を取得 ```cs using (var context = new BloggingContext()) { var blog = context.Blogs .Single(b => b.BlogId == 1); } ``` ### フィルタリング ```cs using (var context = new BloggingContext()) { var blogs = context.Blogs .Where(b => b.Url.Contains("dotnet")) .ToList(); } ``` ## 関連するデータの取得 Entity Framework Core におけるリレーションシップについては以下を参照してください。 - http://kuttsun.blogspot.jp/2018/01/entity-framework-core_11.html ここでは上記のときと同じ以下のモデルを例とします。 ```cs // Blog is the principal entity public class Blog { // Blog.BlogId is the principal key // (in this case it is a primary key rather than an alternate key) public int BlogId { get; set; } public string Url { get; set; } // Blog.Posts is a collection navigation property public List
Posts { get; set; } } // Post is the dependent entity public class Post { public int PostId { get; set; } public string Title { get; set; } public string Content { get; set; } // Post.BlogId is the foreign key public int BlogId { get; set; } // Post.Blog is a reference navigation property // Post.Blog is the inverse navigation property of Blog.Posts (and vice versa) public Blog Blog { get; set; } } ``` [公式サイト](https://docs.microsoft.com/en-us/ef/core/querying/related-data)によると、関連データを取得する際のO/Rマッピングのパターンは以下の3パターンがあるようです。 - **Eager loading** 関連するデータが初期クエリの一部としてデータベースからロードされる - **Explicit loading** 関連するデータが後でデータベースから明示的にロードされる - **Lazy loading** Navigation property にアクセスしたときに関連するデータがデータベースから透過的にロードされる 直訳しただけですが、分かったような分からないような・・・。 以下、ほぼ訳しただけの内容です。 ### Eager loading `Include` メソッドを使用して、クエリの結果に含める関連データを指定できます。 以下の例では、`blogs` には、関連する `Posts` プロパティのインスタンスを持った状態でデータが取得されます。 ```cs using (var context = new BloggingContext()) { var blogs = context.Blogs .Include(blog => blog.Posts) .ToList(); } ``` もし `Include` がなかったら、`blogs` の `Posts` プロパティは null になります。 複数の関連データを取得したい場合でも、以下のように1つのクエリで指定できます。 ```cs using (var context = new BloggingContext()) { var blogs = context.Blogs .Include(blog => blog.Posts) .Include(blog => blog.Owner) .ToList(); } ``` #### 複数のレベルのデータを取得 エンティティが複数の関係を持つ場合、`ThenInclude` メソッドを使用して複数のレベルの関連データを含めることができます。 次の例では、すべての `blog` 関連する `post`、および各 `post` の `Author` を読み込みます。 ```cs using (var context = new BloggingContext()) { var blogs = context.Blogs .Include(blog => blog.Posts) .ThenInclude(post => post.Author) .ToList(); } ``` さらに `ThenInclude` を呼び出すことで、連鎖的に関連データを取得できます。 ```cs using (var context = new BloggingContext()) { var blogs = context.Blogs .Include(blog => blog.Posts) .ThenInclude(post => post.Author) .ThenInclude(author => author.Photo) .ToList(); } ``` これらを組み合わせて、1つのクエリでの複数のレベルおよび複数のルートから関連データを取得できます。 ```cs using (var context = new BloggingContext()) { var blogs = context.Blogs .Include(blog => blog.Posts) .ThenInclude(post => post.Author) .ThenInclude(author => author.Photo) .Include(blog => blog.Owner) .ThenInclude(owner => owner.Photo) .ToList(); } ``` 含まれているエンティティの1つに複数の関連エンティティを含めることができます。 例えば、`blogs` に対するクエリのおいて、`Posts` を取得し、さらに `Posts` の中の `Author` と `Tags` を取得したい場合などです。 これを行うには、それぞれに対してルートからインクルードパスを指定する必要があります。 例えば、以下のように、`Blog -> Posts -> Author` `Blog -> Posts -> Tags` のようにします。 ```cs using (var context = new BloggingContext()) { var blogs = context.Blogs .Include(blog => blog.Posts) .ThenInclude(post => post.Author) .Include(blog => blog.Posts) .ThenInclude(post => post.Tags) .ToList(); } ``` #### 無視される内容 クエリが開始されたときのエンティティのインスタンスを返さないようにクエリを変更すると、`Include` 演算子は無視されます。 次の例では、`Include` 演算子は `Blog` に基づいていますが、`Select` 演算子はクエリを変更して匿名型を返すために使用されています。 この場合、`Include` 演算子は何の効果もありません。 ```cs using (var context = new BloggingContext()) { var blogs = context.Blogs .Include(blog => blog.Posts) .Select(blog => new { Id = blog.BlogId, Url = blog.Url }) .ToList(); } ``` デフォルトでは、`Include` 演算子が無視されると、EF Core は警告をだします。 ロギング出力の表示の詳細については、[Logging](https://docs.microsoft.com/en-us/ef/core/miscellaneous/logging) を参照してください。 `Include` 演算子が無視されたときに、例外を投げるか何もしないか、振る舞いを変更することができます。 これは、コンテキストのオプションを設定するときに行われます。 (通常は `DbContext.OnConfiguring` または ASP.NET Core を使用している場合は `Startup.cs` で行います。) ```cs protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder .UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=EFQuerying;Trusted_Connection=True;ConnectRetryCount=0") .ConfigureWarnings(warnings => warnings.Throw(CoreEventId.IncludeIgnoredWarning)); } ``` ### Explicit loading Navigation property は、`DbContext.Entry(...)` API を使用して明示的に読み込むことができます。 ```cs using (var context = new BloggingContext()) { var blog = context.Blogs .Single(b => b.BlogId == 1); context.Entry(blog) .Collection(b => b.Posts) .Load(); context.Entry(blog) .Reference(b => b.Owner) .Load(); } ``` 関連するエンティティを返すクエリを個別に実行することによって、Navigation property を明示的にロードすることもできます。 #### Querying related entities また、Navigation property の内容を表す LINQ クエリを取得することもできます。 これにより、関連エンティティをメモリにロードせずに `Count` 演算子を実行したりすることができます。 ```cs using (var context = new BloggingContext()) { var blog = context.Blogs .Single(b => b.BlogId == 1); var postCount = context.Entry(blog) .Collection(b => b.Posts) .Query() .Count(); } ``` また、関連エンティティをフィルタリングしてメモリにロードすることもできます。 ```cs using (var context = new BloggingContext()) { var blog = context.Blogs .Single(b => b.BlogId == 1); var goodPosts = context.Entry(blog) .Collection(b => b.Posts) .Query() .Where(p => p.Rating > 3) .ToList(); } ``` ### Lazy loading EF Core ではまだサポートされていません。 ### データのリレーションシップとシリアライズ EF Core は自動的に Navigation property を修正するので、オブジェクトグラフに循環構造を持つことになります。 例えば、`blog` とそれに関連する `Posts` を読み込むと、`Posts` コレクションに対する参照を持った `blog` オブジェクトという結果になります。 `Posts` コレクション内のそれぞれ要素は、`blog` への参照を持つことになります。 一部のシリアライゼーションフレームワークでは、このような循環は許可されません。 たとえば、Json.NET では循環構造が発見された場合、次の例外をスローします。 > Newtonsoft.Json.JsonSerializationException: Self referencing loop detected for property 'Blog' with type 'MyApplication.Models.Blog'. ASP.NET Core を使用している場合は、オブジェクトグラフで見つかった循環を無視するようにJson.NETを設定できます。 これは `Startup.cs` の `ConfigureServices(...)` メソッドで行われます。
Read more
2018/01/15
image
NO IMAGE
draw.io で作成した SVG で not supported by viewer と表示される。
update
event_note
label
draw.io
draw.io で作成した SVG を別のビューワーで開いたときときに、特に日本語を使用している箇所で not supported by viewer と表示される場合の対処方法です。
まず対象の図を選択します。 右側のサイドメニューより、以下の2つのチェックを OFF にします。 - Word Wrap - Formatted Text https://desk.draw.io/support/solutions/articles/16000042487-why-does-the-text-of-svg-export-sometimes-not-display-correctly-in-ie-and-some-svg-editors-
Read more
2018/01/14
image
NO IMAGE
dotnet ef コマンドを有効にする
update
event_note
label
Entity Framework Core
dotnet コマンドはクロスプラットフォームに対応した CLI ツールですが、これの Entity Framework Core による拡張コマンドである `dotnet ef` コマンドを使えるようにする方法です。
`dotnet ef` コマンドは dotnet CLI の Entity Framework Core 拡張ツールであり、`Microsoft.EntityFrameworkCore.Tools.DotNet` で提供されています。 そして、これはNuGet パッケージマネージャーコンソールによる`Install-Package` コマンドや GUI によるインストールでは有効にならないようです。 このパッケージを追加するには、プロジェクトファイル(`.csproj`)をエディタで開き、`Project` 配下に以下を追記します。 ```xml
``` バージョンは必要に応じて変更します。 このあと `dotnet restore` を実行すれば `dotnet ef` コマンドが使用できるようになります。 詳細は以下に記載されています。 - https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/migrations#entity-framework-core-nuget-packages-for-migrations - https://docs.microsoft.com/en-us/ef/core/get-started/netcore/new-db-sqlite#install-entity-framework-core - https://github.com/aspnet/EntityFrameworkCore/issues/8996
Read more
2018/01/11
image
NO IMAGE
Entity Framework Core におけるリレーションシップについて
update
event_note
label
Entity Framework Core
公式サイトに Entity Framework Core のリレーションシップについての記述がありますが、私のような初心者にはなかなか難しいので、和訳を兼ねて自分なりにまとめてみました。
- https://docs.microsoft.com/en-us/ef/core/modeling/relationships しかし、後半に行くほどただ和訳しただけになってしまいました・・・。 ## 環境 - Visual Studio 2017 - .NET Core 2.0 - Entity Framework Core 2.0 ## 用語 リレーションシップについて説明するにあたり、いろいろな用語が出てくるので、公式サイトではまず用語の定義から説明されています。 - https://docs.microsoft.com/en-us/ef/core/modeling/relationships 稚拙な訳ですが、とりあえずまとめてみました。 - **Dependent entity** 外部キーのプロパティを含んだエンティティ。リレーションシップにおける「子」になる。 - **Principal entity** プライマリ/代替キーのプロパティを含むエンティティ。リレーションシップにおける「親」になる。 - **Foreign key (外部キー)** 関連する Principal entity のキーを格納するための Dependent entity 内のプロパティ。 - **Principal key** Principal entity の主キーまたは代替キー。 - **Navigation property** Principal entity と Dependent entity の両方またはどちらかに定義される、関連するエンティティへの参照を含むプロパティ。 - **Collection navigation property** 多くの関連するエンティティへの参照を含む Navigation property。 - **Reference navigation property** 単一の関連エンティティへの参照を保持する Navigation property。 - **Inverse navigation property** 特定のナビゲーションプロパティについて説明するときおいて、リレーションシップのもう一方の Navigation property のこと。 以下にコードと用語の関係を示します。 ```cs // Blog is the principal entity public class Blog { // Blog.BlogId is the principal key // (in this case it is a primary key rather than an alternate key) public int BlogId { get; set; } public string Url { get; set; } // Blog.Posts is a collection navigation property public List
Posts { get; set; } } // Post is the dependent entity public class Post { public int PostId { get; set; } public string Title { get; set; } public string Content { get; set; } // Post.BlogId is the foreign key public int BlogId { get; set; } // Post.Blog is a reference navigation property // Post.Blog is the inverse navigation property of Blog.Posts (and vice versa) public Blog Blog { get; set; } } ``` ## Conventions ※ Convention だと意味がよくわかりませんが、ここでは EF Core の規則とでも言えばよいのでしょうかね。 Convention により、ある型に Navigation property があった場合にリレーションシップが作られます。 そのプロパティの指す型が現在のデータベースプロバイダーによってスカラ型としてマップされない場合、プロパティは Navigation property と見なされます。 Convention によるリレーションシップは、常に Principal entity の主キーを対象とします。 代替キーをターゲットにするには、Fluent API を使用して追加の設定を行う必要があります。 ## リレーションシップの完全な定義 最も一般的なリレーションシップのパターンは、そのリレーションシップの両端に定義された Navigation property と、Dependent entity クラス内に定義された外部キーを持つことです。 これは上記のコードの例で言えば、以下のことを指します。 - `Blog` クラス内に Navigation property として `Posts` を持つ - `Post` クラス内に Navigation property として `Blog` を持つ - `Post` クラス内に 外部キーとして `BlogId` を持つ 2つの型の間に `Navigation property` のペアがある場合、それらのプロパティはそのリレーションシップにおける `Inverse navigation property` として互いに設定されます。 **Dependent entity** に以下のいずれかの名前のプロパティがあれば、それは外部キーとして設定されます。 - `
` - `
` - `
` 上記の例で言えば、`Post` クラス内に、`BlogId` または `BlogBlogId` というプロパティがあればそれが外部キーとみなされることになり、`BlogId` が存在するため、これが外部キーとして設定されます。 もし2つの型の間に Navigation property が複数あれば、Convention によってリレーションシップは作成されないため、手動で設定する必要があります。 ## 外部キーがない場合 Dependent entity 内には外部キーのプロパティを持つことが推奨されますが、必須ではありません。 もし外部キーのプロパティがなければ、`
` という隠れた外部キーが用意されます。 (詳細は [Shadow Property](https://docs.microsoft.com/en-us/ef/core/modeling/shadow-properties) を参照) ```cs public class Blog { public int BlogId { get; set; } public string Url { get; set; } public List
Posts { get; set; } } public class Post { public int PostId { get; set; } public string Title { get; set; } public string Content { get; set; } // 外部キーなし public Blog Blog { get; set; } } ``` ## Single Navigation Property 1つの Navigation property だけを持つ場合(Inverse navigation と外部キーのプロパティがない場合)でも、Convention によってリレーションシップを持つことができます。 単一の Navigation property と外部キーを持つこともできます。 ``` public class Blog { public int BlogId { get; set; } public string Url { get; set; } // 単一の Navigation property だけを持つ public List
Posts { get; set; } } public class Post { public int PostId { get; set; } public string Title { get; set; } public string Content { get; set; } } ``` ## Cascade Delete ※ Cascade Delete は直訳すると連鎖的な削除といった感じでしょうか? Convention により、cascade delete は、必須のリレーションシップに対しては Cascade に、オプションのリレーションシップに対しては ClientSetNull に設定されます。 Cascade とは、依存するエンティティも削除されることを意味します。 ClientSetNull とは、メモリーにロードされない Dependent entity は変更されないため、手動で削除するか、有効な principal entity を指すように更新する必要があることを意味します。 メモリーにロードされたエンティティの場合、EF Core は外部キーのプロパティを null にセットしようとします。 必須のリレーションシップとオプションのリレーションシップについては [Required and Optional Relationships](https://docs.microsoft.com/en-us/ef/core/modeling/relationships#required-and-optional-relationships) を参照してください。 Convention によって行われる削除の振る舞いの違いについては、[Cascade Delete](https://docs.microsoft.com/en-us/ef/core/saving/cascade-delete) を参照してください。 ## Data Annotations リレーションシップを設定には、`[ForeignKey]` と `[InverseProperty]` の2つの Data Annotations があります。 ### [ForeignKey] Data Annotations を使用して、特定のリレーションシップの外部キープロパティーとして使用するプロパティーを設定することができます。 これは通常、外部キーのプロパティが Conventions によって検出されない場合に実行されます。 ```cs // Blog is the principal entity public class Blog { // Blog.BlogId is the principal key (in this case it is a primary key rather than an alternate key) public int BlogId { get; set; } public string Url { get; set; } // Blog.Posts is a collection navigation property public List
Posts { get; set; } } // Post is the dependent entity public class Post { public int PostId { get; set; } public string Title { get; set; } public string Content { get; set; } public int BlogForeignKey { get; set; } // Post.Blog is a reference navigation property [ForeignKey("BlogForeignKey")] public Blog Blog { get; set; } } ``` `[ForeignKey]` はリレーションシップ内のどこかの Navigation property に配置できます。 dependent entity クラス内の Navigation property に行く必要はありません。 ### [InverseProperty] You can use the Data Annotations to configure how navigation properties on the dependent and principal entities pair up. This is typically done when there is more than one pair of navigation properties between two entity types. Data Annotations を使用して、Dependent entity と Principal entity に Navigation property のペアを設定できます。 これは通常、2つのエンティティの間に1つ以上の Navigation property のペアがある場合に実行されます。 ```cs public class Post { public int PostId { get; set; } public string Title { get; set; } public string Content { get; set; } public int AuthorUserId { get; set; } public User Author { get; set; } public int ContributorUserId { get; set; } public User Contributor { get; set; } } public class User { public string UserId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } [InverseProperty("Author")] public List
AuthoredPosts { get; set; } [InverseProperty("Contributor")] public List
ContributedToPosts { get; set; } } ``` ## Fluent API **Fluent API** でリレーションシップを設定するためには、リレーションシップを構成する Navigation property を指定します。 `HasOne` または `HasMany` は、設定を開始するエンティティの Navigation property を指定します。 その後、`WithOne` または `WithMany` を呼び出して、Inverse navigation property を指定します。 `HasOne` と `WithOne` は Navigation property に対して使用され、`HasMany` と `WithMany` は collection navigation properties に対して使用されます。 ```cs class MyContext : DbContext { public DbSet
Blogs { get; set; } public DbSet
Posts { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity
() .HasOne(p => p.Blog) .WithMany(b => b.Posts); } } public class Blog { public int BlogId { get; set; } public string Url { get; set; } public List
Posts { get; set; } } public class Post { public int PostId { get; set; } public string Title { get; set; } public string Content { get; set; } public Blog Blog { get; set; } } ``` ### Single Navigation Property Navigation property が1つしかない場合、 `WithOne` と `WithMany` には引数なしのオーバーロードがあります。 これは、リレーションシップのもう一方の端には、概念的に参照またはコレクションがあることを示しますが、エンティティクラスには Navigation property は含まれていません。 ```cs class MyContext : DbContext { public DbSet
Blogs { get; set; } public DbSet
Posts { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity
() .HasMany(b => b.Posts) .WithOne(); } } public class Blog { public int BlogId { get; set; } public string Url { get; set; } public List
Posts { get; set; } } public class Post { public int PostId { get; set; } public string Title { get; set; } public string Content { get; set; } } ``` ### Foreign Key Fluent APIを使用して、特定のリレーションシップの外部キープロパティーとして使用するプロパティーを設定できます。 ```cs class MyContext : DbContext { public DbSet
Blogs { get; set; } public DbSet
Posts { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity
() .HasOne(p => p.Blog) .WithMany(b => b.Posts) .HasForeignKey(p => p.BlogForeignKey); } } public class Blog { public int BlogId { get; set; } public string Url { get; set; } public List
Posts { get; set; } } public class Post { public int PostId { get; set; } public string Title { get; set; } public string Content { get; set; } public int BlogForeignKey { get; set; } public Blog Blog { get; set; } } ``` 以下のコードは複合外部キーを設定する方法です。 ```cs class MyContext : DbContext { public DbSet
Cars { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity
() .HasKey(c => new { c.State, c.LicensePlate }); modelBuilder.Entity
() .HasOne(s => s.Car) .WithMany(c => c.SaleHistory) .HasForeignKey(s => new { s.CarState, s.CarLicensePlate }); } } public class Car { public string State { get; set; } public string LicensePlate { get; set; } public string Make { get; set; } public string Model { get; set; } public List
SaleHistory { get; set; } } public class RecordOfSale { public int RecordOfSaleId { get; set; } public DateTime DateSold { get; set; } public decimal Price { get; set; } public string CarState { get; set; } public string CarLicensePlate { get; set; } public Car Car { get; set; } } ``` `HasForeignKey(...)` の文字列オーバーロードを使用して、Shadow property を外部キーとして構成できます。 (詳細は、[Shadow Properties](https://docs.microsoft.com/en-us/ef/core/modeling/shadow-properties) を参照)。 外部キーとして使用する前に、Shadow property をモデルに明示的に追加することを推奨します(下記参照)。 ```cs class MyContext : DbContext { public DbSet
Blogs { get; set; } public DbSet
Posts { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { // Add the shadow property to the model modelBuilder.Entity
() .Property
("BlogForeignKey"); // Use the shadow property as a foreign key modelBuilder.Entity
() .HasOne(p => p.Blog) .WithMany(b => b.Posts) .HasForeignKey("BlogForeignKey"); } } public class Blog { public int BlogId { get; set; } public string Url { get; set; } public List
Posts { get; set; } } public class Post { public int PostId { get; set; } public string Title { get; set; } public string Content { get; set; } public Blog Blog { get; set; } } ``` ### Principal Key 外部キーが主キー以外のプロパティーを参照するようにするには、Fluent API を使用してリレーションシップの Principal key のプロパティーを指定します。 Principal key として設定したプロパティは、自動的に代替キーとして設定されます。 (詳細については、[Alternate Keys](https://docs.microsoft.com/en-us/ef/core/modeling/alternate-keys) を参照してください)。 ```cs class MyContext : DbContext { public DbSet
Cars { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity
() .HasOne(s => s.Car) .WithMany(c => c.SaleHistory) .HasForeignKey(s => s.CarLicensePlate) .HasPrincipalKey(c => c.LicensePlate); } } public class Car { public int CarId { get; set; } public string LicensePlate { get; set; } public string Make { get; set; } public string Model { get; set; } public List
SaleHistory { get; set; } } public class RecordOfSale { public int RecordOfSaleId { get; set; } public DateTime DateSold { get; set; } public decimal Price { get; set; } public string CarLicensePlate { get; set; } public Car Car { get; set; } } ``` 次のコードは、Principal key の複合キーを指定する方法を示しています。 ```cs class MyContext : DbContext { public DbSet
Cars { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity
() .HasOne(s => s.Car) .WithMany(c => c.SaleHistory) .HasForeignKey(s => new { s.CarState, s.CarLicensePlate }) .HasPrincipalKey(c => new { c.State, c.LicensePlate }); } } public class Car { public int CarId { get; set; } public string State { get; set; } public string LicensePlate { get; set; } public string Make { get; set; } public string Model { get; set; } public List
SaleHistory { get; set; } } public class RecordOfSale { public int RecordOfSaleId { get; set; } public DateTime DateSold { get; set; } public decimal Price { get; set; } public string CarState { get; set; } public string CarLicensePlate { get; set; } public Car Car { get; set; } } ``` Principal key のプロパティーを指定する順序は、それらが外部キーに指定されている順序と一致していなければなりません。 ### Required and Optional Relationships Fluent API を使用して、リレーションシップが必須かオプションかを設定できます。 最終的には、外部キーのプロパティが必須かオプションかどうかで制御します。 これは、隠れた状態の外部キーを使用している場合に最も便利です。(?) エンティティクラスに外部キーのプロパティがある場合、リレーションシップの必要性に応じて、外部キーのプロパティが必須かオプションかが判断されます。 (詳細は、[Required and Optional properties](https://docs.microsoft.com/en-us/ef/core/modeling/required-optional) を参照)。 ```cs class MyContext : DbContext { public DbSet
Blogs { get; set; } public DbSet
Posts { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity
() .HasOne(p => p.Blog) .WithMany(b => b.Posts) .IsRequired(); } } public class Blog { public int BlogId { get; set; } public string Url { get; set; } public List
Posts { get; set; } } public class Post { public int PostId { get; set; } public string Title { get; set; } public string Content { get; set; } public Blog Blog { get; set; } } ``` ### Cascade Delete Fluent APIを使用すると、特定のリレーションシップの連鎖的な削除処理を明示的に設定できます。 各オプションの詳細については、Saving Data セクションの [Cascade Delete](https://docs.microsoft.com/en-us/ef/core/saving/cascade-delete) を参照してください。 ```cs class MyContext : DbContext { public DbSet
Blogs { get; set; } public DbSet
Posts { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity
() .HasOne(p => p.Blog) .WithMany(b => b.Posts) .OnDelete(DeleteBehavior.Cascade); } } public class Blog { public int BlogId { get; set; } public string Url { get; set; } public List
Posts { get; set; } } public class Post { public int PostId { get; set; } public string Title { get; set; } public string Content { get; set; } public int? BlogId { get; set; } public Blog Blog { get; set; } } ``` ## Other Relationship Patterns ### 一対一 一対一のリレーションシップでは、両方に Reference navigation property があります。 それらは1対多のリレーションシップと同じ規則に従いますが、1つの Dependent entity だけが各 Principal entity に関連していることを保証するために、外部キープロパティに固有のインデックスが導入されています。(?) ```cs public class Blog { public int BlogId { get; set; } public string Url { get; set; } public BlogImage BlogImage { get; set; } } public class BlogImage { public int BlogImageId { get; set; } public byte[] Image { get; set; } public string Caption { get; set; } public int BlogId { get; set; } public Blog Blog { get; set; } } ``` EF は、外部キーのプロパティを検出できるかどうかに基づいて、エンティティの1つを Dependent entity として選択します。(?) 間違ったエンティティが Dependent entity として選択された場合は、Fluent API を使用して修正することができます。 Fluent API でリレーションシップを設定するときは、`HasOne` メソッドと `WithOne` メソッドを使用します。 外部キーを設定するときは、Dependent entity の型を指定する必要があります。 以下のコードの `HasForeignKey` に提供されている汎用パラメータに注意してください。 一対多のリレーションシップでは、Reference navigation property を持つエンティティが Dependent entity であり、コレクションを持つエンティティが Principal entity であることは明らかです。 しかし、一対一のリレーションシップではそのようなことはないため、明示的に定義する必要があります。 ```cs class MyContext : DbContext { public DbSet
Blogs { get; set; } public DbSet
BlogImages { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity
() .HasOne(p => p.BlogImage) .WithOne(i => i.Blog) .HasForeignKey
(b => b.BlogForeignKey); } } public class Blog { public int BlogId { get; set; } public string Url { get; set; } public BlogImage BlogImage { get; set; } } public class BlogImage { public int BlogImageId { get; set; } public byte[] Image { get; set; } public string Caption { get; set; } public int BlogForeignKey { get; set; } public Blog Blog { get; set; } } ``` ### 多対多 結合テーブルを表すエンティティクラスがない多対多のリレーションシップは、まだサポートされていません。 ただし、多対多のリレーションシップは、結合テーブルのエンティティクラスを組み込み、2つの異なる一対多のリレーションシップをマッピングすることで表現できます。 ```cs class MyContext : DbContext { public DbSet
Posts { get; set; } public DbSet
Tags { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity
() .HasKey(t => new { t.PostId, t.TagId }); modelBuilder.Entity
() .HasOne(pt => pt.Post) .WithMany(p => p.PostTags) .HasForeignKey(pt => pt.PostId); modelBuilder.Entity
() .HasOne(pt => pt.Tag) .WithMany(t => t.PostTags) .HasForeignKey(pt => pt.TagId); } } public class Post { public int PostId { get; set; } public string Title { get; set; } public string Content { get; set; } public List
PostTags { get; set; } } public class Tag { public string TagId { get; set; } public List
PostTags { get; set; } } public class PostTag { public int PostId { get; set; } public Post Post { get; set; } public string TagId { get; set; } public Tag Tag { get; set; } } ```
Read more
2018/01/10
image
NO IMAGE
Entity Framework Core の基本的な使い方
update
event_note
label
Entity Framework Core
Entity Framework Core の基本的な使い方についてです。
基本的には公式のドキュメントが充実しているので、それを参考に自分なりにまとめただけです。 - https://docs.microsoft.com/en-us/ef/core/index **追記** 現在では他にも調べたことを以下にまとめていっているので、そちらのほうが参考になるかもしれません。 - http://kuttsun.blogspot.jp/p/blog-page_75.html?max-results=10#efcore ## 環境 - Visual Studio 2017 - .NET Core 2.0 - Entity Framework Core 2.0 ### Entity Framework Core のインストール NuGet でデータベースプロバイダーに応じたパッケージをインストールします。 例えば、SQL Server を使用する場合は ```sh PM> Install-Package Microsoft.EntityFrameworkCore.SqlServer ``` SQLite を使用する場合は ```sh PM> Install-Package Microsoft.EntityFrameworkCore.Sqlite ``` です。 詳細は以下を参照してください。 - https://docs.microsoft.com/en-us/ef/core/providers/ ## モデルの作成 - https://docs.microsoft.com/en-us/ef/core/modeling/index 最初にテーブルレコードとマッピングされるエンティティクラスを作成します。 ここでは例として、以下のようなエンティティクラスを作成します。 ```cs public class Person { public int Id { get; set; } public string Name { get; set; } } ``` これがテーブルの構造になります。 この Person クラスをデータベースに出し入れするため、DbContext クラスを継承したコンテキストクラスを定義します。 ```cs using Microsoft.EntityFrameworkCore; // 中略 public class PersonDbContext : DbContext { public DbSet
Persons { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { // データベースプロバイダーに応じた設定 } } ``` `OnConfiguring()` メソッドの中ではデータベースへの接続文字列などを設定しますが、プロバイダーに応じて設定が異なるので、ここでは省略します。 Entity Framework Core で使用可能なプロバイダーについては以下を参照してください。 - https://docs.microsoft.com/en-us/ef/core/providers/ ### データベースとのマッピング方法を指定する 文字列のサイズや NOT NULL 制約など、データベースとの O/R マッピングの方法を指定します。 マッピング方法の指定には属性を使って指定する **Data Annotation 方式**と、`OnModelCreating()` メソッド内にコードで記述する **Fluent API 方式**があるようです。 例えば、前述の Person クラスで Name プロパティを必須にしたい場合は以下のように記述します。 **Data Annotation** ```cs public class Person { public int Id { get; set; } [Required] public string Name { get; set; } } ``` **Fluent API** ```cs public class PersonDbContext : DbContext { protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity
().Property(x => x.Name).IsRequired(); base.OnModelCreating(modelBuilder); } } ```` 個人的に Data Annotation 方式のほうがわかりやすくて好きですが、複合キーやリレーションシップなどに関する情報は現時点ではFluent API 方式でしか設定できないようです。 - https://docs.microsoft.com/en-us/ef/core/modeling/index ### 主キー Entity Framework Core では `id` `Id` `
ID` などのプロパティが存在した場合、これが主キーであると自動的に判断されるようです。 Data Annotation で `[key]` で明示的に指定する方法もあります。 - https://docs.microsoft.com/en-us/ef/core/modeling/keys ## Code First によるデータベースの作成 `EnsureCreated()` メソッドを実行すると、モデルを元にデータベースが作成されます。 ```cs // データベースの作成 using (var db = new PersonDbContext()) { await db.Database.EnsureCreatedAsync(); } ``` 既にデータベースが存在する場合は何も実行されないようです。 その場合、データベースとモデルの整合性はチェックされないようなので、注意が必要です。 - https://docs.microsoft.com/en-us/ef/core/api/microsoft.entityframeworkcore.storage.idatabasecreator ## CRUD 操作 基本的な CRUD 操作の方法です。 - https://docs.microsoft.com/en-us/ef/core/saving/basic ### レコードの追加 ```cs using (var db = new PersonDbContext()) { var person = new Person { Name = "Hoge" }; db.Persons.Add(person); db.SaveChanges(); } ``` ### レコードの取得 ```cs using (var db = new PersonDbContext()) { foreach (var person in db.Persons) { Console.WriteLine($"ID={person.Id}, Name={person.Name}"); } } ``` ### レコードの更新 ```cs int id = 1; using (var db = new PersonDbContext()) { var person = db.Persons.Where(x => x.Id == id).FirstOrDefault(); person.Name = name; db.SaveChanges(); } ``` ### レコードの削除 ```cs int id = 1; using (var db = new PersonDbContext()) { var person = db.Persons.Where(x => x.Id == id).FirstOrDefault(); db.Persons.Remove(person); db.SaveChanges(); } ``` ## 参考 URL - https://docs.microsoft.com/en-us/ef/core/index - http://www.learnentityframeworkcore.com/ - http://ryuichi111std.hatenablog.com/entry/2016/11/08/023809 - http://gooner.hateblo.jp/entry/2016/03/04/071400 - https://blogs.msdn.microsoft.com/nakama/2016/07/07/aspnetcore10-part2/ - http://ohke.hateblo.jp/entry/2017/03/03/000000
Read more
2018/01/07
image
NO IMAGE
コマンド "dotnet-ef" に一致する実行可能ファイルが見つかりません
update
event_note
label
Entity Framework Core
`dotnet ef` コマンドを実行しようとしたとき、`コマンド "dotnet-ef" に一致する実行可能ファイルが見つかりません` と表示される場合の対処方法です。
`dotnet ef` コマンドは dotnet CLI の Entity Framework Core 拡張ツールであり、`Microsoft.EntityFrameworkCore.Tools.DotNet` で提供されています。 そして、これはNuGet パッケージマネージャーコンソールによる`Install-Package` コマンドや GUI によるインストールでは有効にならないようです。 このパッケージを追加するには、プロジェクトファイル(`.csproj`)をエディタで開き、`Project` 配下に以下を追記します。 ```xml
``` バージョンは必要に応じて変更します。 このあと `dotnet restore` を実行すれば `dotnet ef` コマンドが使用できるようになります。 詳細は以下に記載されています。 - https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/migrations#entity-framework-core-nuget-packages-for-migrations - https://docs.microsoft.com/en-us/ef/core/get-started/netcore/new-db-sqlite#install-entity-framework-core - https://github.com/aspnet/EntityFrameworkCore/issues/8996
Read more
新しい投稿
前の投稿
ホーム
Translate
Popular Posts
TortoiseGit でコミットメッセージを変更する
image
NO IMAGE
TortoiseGit でブランチ間の差分を見る
image
NO IMAGE
[ASP.NET Core] 前のページ(遷移元)の URL を取得する
image
NO IMAGE
外部 DLL を NuGet パッケージに含める方法
image
NO IMAGE
[C#] SonarQube で .NET アプリケーションのコード解析を行う
image
NO IMAGE
[ASP.NET Core] Form value count limit 1024 exceeded のエラーが発生した
image
NO IMAGE
マージ元ブランチとマージ先ブランチ
TortoiseGit でリモートリポジトリのタグを削除する
image
NO IMAGE
C# で GitHub からリリースバージョンを取得する
[Jenkins] エラー 1069: ログオンに失敗したため、サービスを開始できませんでした。
Labels
.NET Core
31
.NET Framework
17
.NET Standard
2
AdminLTE
1
Apache
3
AppVeyor
2
AsciiDoc
3
ASP.NET Core
55
Atom
4
AWS
2
AWS Cloud9
4
blockdiag
1
Blogger
10
Bootstrap
3
C/C++
6
C#
106
CentOS
3
Chrome
1
Chronograf
3
Codecov
1
CSS
1
Docker
28
DokuWiki
4
Doxygen
1
draw.io
1
Electron.NET
2
Entity Framework Core
9
Excel
2
FFmpeg
2
Firefox
5
Git
12
GitBook
4
GitBucket
7
GitHub
7
GitLab
30
Go
1
Google
1
Google Cloud Platform
1
Grafana
5
HTML
5
IIS
8
InfluxDB
6
JavaScript
7
Jenkins
7
Linux
25
Log4View
1
MahApps.Metro
3
MaterialDesignInXamlToolkit
1
MVC
1
MVVM
6
NLog
3
Node.js
3
npm
1
OpenSSL
3
ownCloud
2
Pine Script
1
PlantUML
5
PowerShell
7
Prism
2
Python
11
Razor
3
Redmine
30
remark.js
2
rocketchat
4
Ruby
3
SignalR
1
Socket.IO
1
SonarQube
5
Sphinx
10
SQL Server
5
SQLite
1
t
1
TestLink
2
Tomcat
2
TortoiseGit
10
TortoiseSVN
2
Trading View
1
Travis CI
1
Ubuntu
13
Visual Studio
39
Visual Studio Code
9
Vue.js
8
Windows
56
Windows 10
4
Windows ADK
1
Windows API
2
Windows Embedded
4
wkhtmltopdf
2
Word
3
WPF
12
WSL
1
Xamarin
1
xUnit
5
アプリケーション
1
デザインパターン
1
テスト
3
バッチファイル
2
ぴよ
3
プログラミング
3
ライセンス
1
ラベル
3
ラベル1
2
英語
2
雑記
1
書籍
1
数学
1
正規表現
1
Blog Archive
►
2022
(1)
►
2月
(1)
►
2021
(24)
►
5月
(7)
►
4月
(8)
►
3月
(2)
►
2月
(2)
►
1月
(5)
►
2020
(60)
►
12月
(1)
►
11月
(3)
►
10月
(3)
►
9月
(3)
►
8月
(3)
►
7月
(7)
►
6月
(7)
►
5月
(2)
►
4月
(6)
►
3月
(6)
►
2月
(7)
►
1月
(12)
►
2019
(92)
►
12月
(13)
►
11月
(9)
►
10月
(3)
►
9月
(2)
►
8月
(3)
►
7月
(5)
►
6月
(11)
►
5月
(6)
►
4月
(17)
►
3月
(9)
►
2月
(6)
►
1月
(8)
▼
2018
(100)
►
12月
(1)
►
11月
(11)
►
10月
(8)
►
9月
(6)
►
8月
(10)
►
7月
(10)
►
6月
(8)
►
5月
(9)
►
4月
(8)
►
3月
(14)
►
2月
(4)
▼
1月
(11)
Entity Framework Core におけるデータの保存
Moq のインストール
ASP.NET Core で SignalR を使用する
Firefox で英単語を簡単に調べられるアドオン
画像を svg から emf に変換する
Entity Framework Core におけるデータの取得
draw.io で作成した SVG で not supported by viewer と表示される。
dotnet ef コマンドを有効にする
Entity Framework Core におけるリレーションシップについて
Entity Framework Core の基本的な使い方
コマンド "dotnet-ef" に一致する実行可能ファイルが見つかりません
►
2017
(117)
►
12月
(14)
►
11月
(20)
►
10月
(17)
►
9月
(19)
►
8月
(10)
►
7月
(8)
►
6月
(3)
►
5月
(6)
►
4月
(5)
►
3月
(2)
►
2月
(8)
►
1月
(5)
►
2016
(91)
►
12月
(5)
►
11月
(9)
►
10月
(11)
►
9月
(9)
►
8月
(6)
►
7月
(14)
►
6月
(14)
►
5月
(11)
►
4月
(10)
►
3月
(2)
►
2015
(23)
►
12月
(4)
►
11月
(2)
►
10月
(8)
►
9月
(8)
►
7月
(1)
►
2013
(3)
►
11月
(1)
►
9月
(1)
►
7月
(1)
►
2012
(2)
►
7月
(1)
►
6月
(1)
►
2011
(1)
►
9月
(1)
►
2009
(1)
►
7月
(1)
►
2008
(2)
►
11月
(1)
►
7月
(1)
►
2007
(3)
►
10月
(3)