using (var context = new ShoppingContext())
{
var product = context.Products.Single(x => x.Name == "Test");
context.Products.Remove(product); // 削除
context.Remove(product); // 削除(こちらでもOK)
context.SaveChanges(); // 削除の適用
}
Method | Usage |
---|---|
Add |
Adds a new entity to DbContext with Added state and starts tracking it.
This new entity data will be inserted into the database when SaveChanges() is called.
|
AddAsync | Asynchronous method for adding a new entity to DbContext with Added state and starts tracking it.
This new entity data will be inserted into the database when SaveChangesAsync() is called.
|
AddRange |
Adds a collection of new entities to DbContext with Added state and starts tracking it.
This new entity data will be inserted into the database when SaveChanges() is called.
|
AddRangeAsync | Asynchronous method for adding a collection of new entities which will be saved on SaveChangesAsync(). |
Attach |
Attaches a new or existing entity to DbContext with Unchanged state and starts tracking it.
|
AttachRange |
Attaches a collection of new or existing entities to DbContext with Unchanged state and starts tracking it.
|
Entry |
Gets an EntityEntry for the given entity. The entry provides access to change tracking information and operations for the entity.
|
Find | Finds an entity with the given primary key values. |
FindAsync | Asynchronous method for finding an entity with the given primary key values. |
Remove | Sets Deleted state to the specified entity which will delete the data when SaveChanges() is called. |
RemoveRange | Sets Deleted state to a collection of entities which will delete the data in a single DB round trip when SaveChanges() is called. |
SaveChanges | Execute INSERT, UPDATE or DELETE command to the database for the entities with Added, Modified or Deleted state. |
SaveChangesAsync | Asynchronous method of SaveChanges() |
Set | Creates a DbSet that can be used to query and save instances of TEntity. |
Update | Attaches disconnected entity with Modified state and start tracking it. The data will be saved when SaveChagnes() is called. |
UpdateRange | Attaches a collection of disconnected entities with Modified state and start tracking it. The data will be saved when SaveChagnes() is called. |
OnConfiguring | Override this method to configure the database (and other options) to be used for this context. This method is called for each instance of the context that is created. |
OnModelCreating | Override this method to further configure the model that was discovered by convention from the entity types exposed in DbSet properties on your derived context. |
https://www.entityframeworktutorial.net/efcore/entity-framework-core-dbcontext.aspx
Extensions/EFCoreDump.cs に以下の内容で保存
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Query.Internal;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Query;
//using System.Collections.Generic;
//using System.Text;
namespace Extensions
{
public static class EFCoreDump
{
private static readonly TypeInfo QueryCompilerTypeInfo = typeof(QueryCompiler).GetTypeInfo();
private static readonly FieldInfo QueryCompilerField = typeof(EntityQueryProvider).GetTypeInfo().DeclaredFields.First(x => x.Name == "_queryCompiler");
private static readonly FieldInfo QueryModelGeneratorField = QueryCompilerTypeInfo.DeclaredFields.First(x => x.Name == "_queryModelGenerator");
private static readonly FieldInfo DataBaseField = QueryCompilerTypeInfo.DeclaredFields.Single(x => x.Name == "_database");
private static readonly PropertyInfo DatabaseDependenciesField = typeof(Database).GetTypeInfo().DeclaredProperties.Single(x => x.Name == "Dependencies");
public static string ToSql<TEntity>(this IQueryable<TEntity> query) where TEntity : class
{
var queryCompiler = (QueryCompiler)QueryCompilerField.GetValue(query.Provider);
var modelGenerator = (QueryModelGenerator)QueryModelGeneratorField.GetValue(queryCompiler);
var queryModel = modelGenerator.ParseQuery(query.Expression);
var database = (IDatabase)DataBaseField.GetValue(queryCompiler);
var databaseDependencies = (DatabaseDependencies)DatabaseDependenciesField.GetValue(database);
var queryCompilationContext = databaseDependencies.QueryCompilationContextFactory.Create(false);
var modelVisitor = (RelationalQueryModelVisitor)queryCompilationContext.CreateQueryModelVisitor();
modelVisitor.CreateQueryExecutor<TEntity>(queryModel);
var sql = modelVisitor.Queries.First().ToString();
return sql;
}
}
}
using Extensions;
var datas1 = _context.MyTable.ToList();
var datas2 = _context.MyTable.FromSql( "SELECT * FROM MyTable" ).ToList();
とすると自動的にデバッグコンソールに SQL 文が出力されます。 また任意のタイミングで取り出したいときは次のようにして Tosql() メソッドで取り出すことができます
string sql_result = _context.MyTable.FromSql( "SELECT * FROM MyTable" ).Tosql();
コードファーストではまず Model ファイルを変更してから、マイグレーションコマンドを実行します。
(例: Models/Memo.cs)の中のテーブル定義を変更する
public class Memo
{
public long ID { get; set; }
[Required]
public string Title { get; set; }
public string Content { get; set; }
}
dotnet ef migrations add <任意の文字列>
<任意の文字列> は 日付やモデル名変更内容を記述するといいでしょう
20201231_Memo_add_Content_column
dotnet ef migrations add 20201231_Memo_add_Content_column
dotnet ef database update
マイグレーションファイルの一覧を表示
dotnet ef migrations list
マイグレーション名の一覧が表示されます。
dotnet ef database update <戻したいマイグレーション名>
dotnet ef migrations remove
最新のマイグレーションファイル 1件を削除します。 (削除しようとするマイグレーションファイルが既にデータベースに適用されているときは削除エラーとなります)
DBテーブル「Memo」に対して必ず「WHERE isDeleted= 0」条件を加えます。
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Memo>().HasQueryFilter(s => s.isDeleted== 0 ); // WHERE isDeleted= 0 に限定する
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using EFCoreFilterApp1.Models;
namespace EFCoreFilterApp1.Data
{
public class MyContext : DbContext
{
public MyContext(DbContextOptions options) : base(options)
{
}
public DbSet<Memo> Memo { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Memo>().HasQueryFilter(s => s.MYID == 2 ); // WHERE MYID = 2 に限定する
}
}
}
あらかじめこちらで SQL Server へ接続できるユーザーを作成します。
SQL Server へ 「SQL Server認証」でログインするユーザーを作成し .Net アプリのDB接続に使用する|プログラムメモ
.NET Coreでコードファーストを使ってDBを作成するまでは大きく分けて次の手順となります。
・1. csファイルの作成と編集
- モデルクラスの作成
- DBコンテキストの作成
- Startup.cs の ConfigureServices() メソッド内に コンテキスト読込を追加
・2. マイグレーションファイルの生成( dotnet ef migrations add )
・3. マイグレーションの実行( dotnet ef database update )
dotnet コマンドは PowerShell から実行します。(Visual Studioのコンソールではありません。)
Models/Memo.cs を以下のように作成
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace 【アプリ名】.Models
{
public class Memo
{
public int ID { get; set; }
public string Title { get; set; }
}
}
IDを表すカラム名は必ず大文字で「ID」である必要があります。
Data/MyContext.cs を以下の内容で作成
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using 【アプリ名】.Models;
namespace 【アプリ名】.Data
{
public class MyContext : DbContext
{
public MyContext( DbContextOptions options ) : base( options )
{
}
public DbSet<Memo> Memo { get; set; }
}
}
Startup.cs に以下の行を追加
using Microsoft.EntityFrameworkCore; を追加
using Microsoft.EntityFrameworkCore;
public void ConfigureServices(IServiceCollection services)
{
// コンテキストクラスを追加ここから
services.AddDbContext<MyContext>( options => options.UseSqlServer(
Configuration.GetConnectionString( "DefaultConnection" )
) );
// コンテキストクラスを追加ここまで
(options.UseSqlServer)は MS SQL Server を使うときに記述します。
(データベースの種類によって書き換えること)
dotnet tool install --global dotnet-ef
dotnet tool install --global dotnet-ef --version 3.0.0
あと Microsoft.EntityFrameworkCore.SqlServer もインストールしておいてください。
dotnet ef migrations add ver1.0
複数コンテキストがある場合はコンテキストを指定する必要があります。
dotnet ef migrations add __My__Ver1.2__ --context MyContex
このとき Migrations ディレクトリ内に次のようなファイルが生成されます。
20180704061421___My__Ver1.2__.cs
20180704061421___My__Ver1.2__.Designer.cs
dotnet ef migrations add __ApplicationDb__Ver1.2__ --context ApplicationDbContext
dotnet ef database update
dotnet ef database update --context MyContext
データベース全体を Drop します
dotnet ef database drop
dotnet ef database drop -f
複数コンテキストがある場合はコンテキストを指定する必要があります。 (ただしDB全体がdropされるので注意)
dotnet ef database drop --context ApplicationDbContext -f