このようなリレーションを設定してみます
Memo <----- 多対多リレーション -----> Category
namespace EFCoreFilterApp.Models
{
public class Category
{
public int ID { get; set; }
public long TenantID { get; set; }
public string Title { get; set; }
public bool IsDeleted { get; set; }
public ICollection<CategoryMemo> CategoryMemos { get; set; }
}
}
public class Memo
{
public int ID { get; set; }
public int CategoryID { get; set; }
public long TenantID { get; set; }
public string Title { get; set; }
public bool IsDeleted { get; set; }
public ICollection<CategoryMemo> CategoryMemos { get; set; }
}
namespace EFCoreFilterApp.Models
{
public class CategoryMemo
{
public int MemoId { get; set; }
public Memo Memo { get; set; }
public int CategoryId { get; set; }
public Category Category { get; set; }
}
}
namespace EFCoreFilterApp.Data
{
public class MyContext : DbContext
{
public MyContext(DbContextOptions options) : base(options) {}
public DbSet<Memo> Memo { get; set; }
public DbSet<Category> Categories { get; set; }
public DbSet<CategoryMemo> CategoryMemo { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<CategoryMemo>().HasKey(bc => new { bc.MemoId, bc.CategoryId });
}
}
}
Includeメソッドで EagerLoading が行われます。
通常は(n+1)を起こさないためこのメソッドで取得するといいでしょう。
複雑なSQLになるときは実際に発行されるSQL文を見て検討が必要です。
var memos_m4 = _context.Memo
.Include(r => r.CategoryMemos)
.ToList();