タグ「EntityFrameworkCore」での検索

Entity Framework Core で 新規作成 / 更新 / 削除

● Entity Framework Core で 新規作成 / 更新 / 削除

・削除

using (var context = new ShoppingContext())
{
    var product = context.Products.Single(x => x.Name == "Test");
    context.Products.Remove(product); // 削除
    context.Remove(product); // 削除(こちらでもOK)
    context.SaveChanges(); // 削除の適用
}
No.1941
01/14 08:22

edit

EntityFrameworkCore

Entity Framework Core DbContext のメソッド一覧

● entity frame core DbContext のメソッド一覧

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

No.1793
01/13 17:23

edit

EntityFrameworkCore

Entity Framework Core が実際に実行したSQL文を出力する

● Tosql()メソッド 拡張メソッドを作成する

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();
No.1783
06/11 13:29

edit

EntityFrameworkCore

.NET Core コードファーストでDBテーブル定義を変更する

1. 変更したいテーブルのファイルを変更する

コードファーストではまず Model ファイルを変更してから、マイグレーションコマンドを実行します。

(例: Models/Memo.cs)の中のテーブル定義を変更する

    public class Memo
    {
        public long ID { get; set; }
        [Required]
        public string Title { get; set; }
        public string Content { get; set; }
    }

2. dotnet ef migrations add コマンドでマイグレーションファイルを出力する

dotnet ef migrations add <任意の文字列>

<任意の文字列> は 日付やモデル名変更内容を記述するといいでしょう
20201231_Memo_add_Content_column

dotnet ef migrations add 20201231_Memo_add_Content_column

3. マイグレーションの実行

dotnet ef database update

4. マイグレーションを戻す(ロールバック)する

マイグレーションファイルの一覧を表示

dotnet ef migrations list

マイグレーション名の一覧が表示されます。

dotnet ef database update <戻したいマイグレーション名>

5. 不要なマイグレーションファイルを削除する

dotnet ef migrations remove

最新のマイグレーションファイル 1件を削除します。 (削除しようとするマイグレーションファイルが既にデータベースに適用されているときは削除エラーとなります)

No.1782
07/06 13:09

edit

EntityFrameworkCore

Entity Framework Core の global filter

● Entity Framework Core の global filter を適用させる

DBテーブル「Memo」に対して必ず「WHERE isDeleted= 0」条件を加えます。

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Memo>().HasQueryFilter(s => s.isDeleted== 0 );  // WHERE isDeleted= 0 に限定する
        }

● 記述例 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 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 に限定する
        }
    }
}
No.1780
06/10 17:36

edit

EntityFrameworkCore

.NET Core で コードファーストでデータベースを作成する

あらかじめこちらで SQL Server へ接続できるユーザーを作成します。

SQL Server へ 「SQL Server認証」でログインするユーザーを作成し .Net アプリのDB接続に使用する|プログラムメモ

● .NET Core Entity Framework コードファーストの手順

.NET Coreでコードファーストを使ってDBを作成するまでは大きく分けて次の手順となります。

・1. csファイルの作成と編集
    - モデルクラスの作成
    - DBコンテキストの作成
    - Startup.cs の ConfigureServices() メソッド内に コンテキスト読込を追加
・2. マイグレーションファイルの生成( dotnet ef migrations add )
・3. マイグレーションの実行( dotnet ef database update )

dotnet コマンドは PowerShell から実行します。(Visual Studioのコンソールではありません。)

● ・1. csファイルの作成と編集

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 を使うときに記述します。
(データベースの種類によって書き換えること)

● 2. データベーステーブルのマイグレーションの作成の準備( dotnet-ef のインストール)

dotnet tool install --global dotnet-ef
dotnet tool install --global dotnet-ef --version 3.0.0

あと Microsoft.EntityFrameworkCore.SqlServer もインストールしておいてください。

● 2. データベーステーブルのマイグレーションの作成

dotnet ef migrations add ver1.0

● 2. (コンテキストを指定した)データベーステーブルのマイグレーションの作成

複数コンテキストがある場合はコンテキストを指定する必要があります。

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

● 3. データベーステーブルのマイグレーションの実行

dotnet ef database update

● 3. (コンテキストを指定した)データベーステーブルのマイグレーションの実行

dotnet ef database update --context MyContext

● データベースの削除

データベース全体を Drop します

dotnet ef database drop

● データベースの削除(削除確認なし)

dotnet ef database drop -f

● データベースの削除( ApplicationDbContext を使って削除 )

複数コンテキストがある場合はコンテキストを指定する必要があります。 (ただしDB全体がdropされるので注意)

dotnet ef database drop --context ApplicationDbContext -f
No.1266
06/10 16:45

edit

EntityFrameworkCore